0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【問題解決】Scala: ` """\d{4}-\d{2}-\d{2}""".r`でMatchError

Last updated at Posted at 2018-04-09

環境

  • Scala 2.12.4

やりたいこと

scala.util.matching.Regexで正規表現のマッチを行いたいです。

問題

日付を年、月、日に分解するため、以下のソースを実行したところ、scala.MatchErrorが発生しました。

val date = """\d{4}-\d{2}-\d{2}""".r
val date(year, month, day) = "2018-04-01"
//scala.MatchError: 2018-04-01 (of class java.lang.String)

原因・解決方法

正規表現のキャプチャが行われていないためです。
正規表現の数字部分に括弧を付けると、期待通り動きます。

val date = """(\d{4})-(\d{2})-(\d{2})""".r
val date(year, month, day) = "2018-04-01"
//year: String = 2018
//month: String = 04
//day: String = 01

感想

正規表現の問題で、Scalaは関係ないですね。
少しハマったので、記事として残しました。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?