Scala - 如何检查哪个正则表达式模式匹配字符串

时间:2016-12-23 02:33:39

标签: scala

假设我有超过30个正则表达式模式:

val pattern1 = """(pat)(tern)(1)""".r
val pattern2 = """(pat)(tern)(1)""".r
val pattern3 = """(pat)(tern)(1)""".r
...

我想检查哪个模式与字符串匹配。像这样的东西

val s = "MyString"

s match {
 case pattern1 => grup 1 of pattern1
 case pattern2 => grup 2 of pattern2
 case pattern3 => grup 3 of pattern3
 ...
 case _ => "No pattern match"
}

1 个答案:

答案 0 :(得分:0)

在您的情况下,您可以执行以下操作:

val s = "MyString"

s match {
   case k if s.matches(pattern1.regex) => //.....do something
   case k if s.matches(pattern2.regex) => //.....do something
   case k if s.matches(pattern3.regex) => //.....do something
   ...
   case _ => "No pattern match"

}