Scala正则表达式在字符串中间找到匹配项

时间:2018-02-23 19:36:21

标签: regex scala

我在scala中编写了以下代码:

val regex_str = "([a-z]+)(\\d+)".r
"_abc123" match {
  case regex_str(a, n) => "found"
  case _ => "other"
}

返回"其他",但如果我取下前导下划线:

val regex_str = "([a-z]+)(\\d+)".r
"abc123" match {
  case regex_str(a, n) => "found"
  case _ => "other"
}

我得到"found"。我怎样才能找到([a-z]+)(\\d+)而不是刚开始?我已经习惯了其他正则表达式语言,你使用^来指定字符串的开头,缺少它只是获得所有匹配。

3 个答案:

答案 0 :(得分:1)

Scala正则表达式模式默认为“锚定”,即绑定到目标字符串的开头和结尾。

你会得到预期的匹配。

val regex_str = "([a-z]+)(\\d+)".r.unanchored

答案 1 :(得分:0)

嗨,你可能需要这样的东西,

val regex_str = "[^>]([a-z]+)(\\d+)".r
"_abc123" match {
  case regex_str(a, n) => println(s"found $a $n")
  case _ => println("other")
}

这将避免字符串中的第一个字符。

希望这有帮助!

答案 2 :(得分:0)

scala模式匹配中的正则表达式提取器尝试匹配整个字符串。如果你想在开头和结尾跳过一些垃圾字符,请在{+ 1>}前加一个不情愿的量词到正则表达式:

.

输出:

val regex_str = ".*?([a-z]+)(\\d+).*".r
val result = "_!+<>__abc123_%$" match {
  case regex_str(a, n) => s"found a = '$a', n = '$n'"
  case _ => "no match"
}

println(result)

否则,请勿使用与提取器匹配的模式,使用found a = 'abc', n = '123' 查找所有匹配项。