LoginSignup
1
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第5回:String templates

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

String templates

month変数を使って、13 JUN 1992(数字2桁、スペース1桁、月の略語、スペース1桁、数字4桁)のフォーマットで日付と一致するように、以下のコードを書き直します。

val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"

fun getPattern(): String = TODO()

そのまま実行するとテストが失敗します。

Error: match1: An operation is not implemented.
Error: match: An operation is not implemented.
Error: doNotMatch: An operation is not implemented.

問題のポイント

トリプルクォートで囲まれた文字列は、バックスラッシュをバックスラッシュでエスケープする必要がないため、複数行の文字列だけでなく、正規表現のパターンを作成する際にも便利です。
次のパターンは、13.06.1992(数字2桁.数字2桁.数字4桁)という書式の日付にマッチします。

fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""

解答例

トリプルクォートを使うとエスケープする必要がないため、見た目がすっきり書けますね。

val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"

fun getPattern(): String = """\d{2} $month \d{4}"""

ダブルクォートを使うとこのようになります。

val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"

fun getPattern(): String = "\\d{2} $month \\d{4}"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0