在scala中匹配或正则表达式

时间:2016-04-22 12:43:51

标签: regex scala switch-statement pattern-matching regex-group

我有一个像".*(A20).*|.*(B30).*|C"这样的正则表达式。 我想根据找到的匹配函数编写一个返回A20B30的函数。

val regx=".*(A20).*|.*(B30).*".r

"helloA20" match { case regx(b,_) => b; case _ => "" } // A20
"helloB30" match { case regx(b,_) => b; case _ => "" } // null
 "C" match { case regx(b,_) => b case _ => "" }

它返回null因为我没有考虑第二组。在我的实际代码中,我有很多这样的组。我想返回匹配的字符串。请帮我找一个解决方案。

2 个答案:

答案 0 :(得分:3)

轻松!它应该是这样的:

val regx="^(.*(B30|A20).*|(C))$".r

演示:https://regex101.com/r/nA6dQ9/1

然后你得到每个组的数组中的第二个值。 This is what I mean!

这样,无论有多少种可能,你只有一个小组。

答案 1 :(得分:1)

你很亲密:

def extract(s: String) = s match {
 case regx(b, _) if b != null => b
 case regx(_, b) if b != null => b
 case _ => "" 
}

extract("helloA20")
res3: String = A20

extract("helloB30")
res4: String = B30

extract("A30&B30")
res6: String = B30

如果你有很多小组,那么使用模式匹配的理解是合理的。此代码将返回第一个匹配或无:

val letters = ('A' to 'Z').toSeq
val regex = letters.map(_.toString).mkString("(", "|", ")").r

def extract(s: String) = {
  for {
    m <- regex.findFirstMatchIn(s)
  } yield m.group(1)
}

extract("A=B=")
extract("dsfdsBA")
extract("C====b")
extract("a====E")

res0: Option[String] = Some(A)
res1: Option[String] = Some(B)
res2: Option[String] = Some(C)
res3: Option[String] = Some(E)