48
43

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: 正規表現でマッチするかどうか調べる方法

Posted at

いろんな方法がある

"1234".matches("""\d{4}""")                       //> res0: Boolean = true

new scala.util.matching.Regex("""\d{4}""").findFirstIn("1234").nonEmpty
                                                  //> res1: Boolean = true

"""\d{4}""".r.findFirstIn("1234").nonEmpty        //> res2: Boolean = true


val dateP1 = """(\d\d\d\d)-(\d\d)-(\d\d)""".r     //> dateP1  : scala.util.matching.Regex = (\d\d\d\d)-(\d\d)-(\d\d)

"2011-07-15" match {
	case dateP1(year, month, day) => true
	case _ => false
}                                                 //> res3: Boolean = true


val dateP1(year, month, day) = "2011-07-15"       //> year  : String = 2011
                                                  //| month  : String = 07
                                                  //| day  : String = 15

dateP1.findAllIn("2011-07-15").matchData.foreach { m =>
	println(m.group(0))
	println(m.group(1))
	println(m.group(2))
	println(m.group(3))
}                                                 //> 2011-07-15
                                                  //| 2011
                                                  //| 07
                                                  //| 15

val dateP2 = new scala.util.matching.Regex("""(\d\d\d\d)-(\d\d)-(\d\d)""", "year", "month", "day")
                                                  //> dateP2  : scala.util.matching.Regex = (\d\d\d\d)-(\d\d)-(\d\d)

dateP2.findAllIn("2011-07-15").matchData.foreach { m =>
	println(m.group("year"))
	println(m.group("month"))
	println(m.group("day"))
}                                                 //> 2011
                                                  //| 07
                                                  //| 15

48
43
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
48
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?