简体   繁体   English

Scala正则表达式模式匹配问题

[英]Scala regex pattern match issue

In the snippet below, part matches just fine, but part2 fails to match. 在下面的代码片段中,部分匹配正常,但part2无法匹配。

val part = """TEXT:123:4:5"""
val part2 = """ text="TEXT:123:4:1">"""
val regex = """TEXT:(\d+):(\d+):(\d+)""".r

def matchAndPrint(text: String) {
  println(text match {
    case regex(num1, num2, num3) => s"$num1:$num2:$num3"
    case _ => "no match"
  })
}
matchAndPrint(part)
matchAndPrint(part2)

I'm not sure how to fix it. 我不确定如何解决它。 Any advice? 有什么建议?

That's what unanchored is for, as shown here . 正如此处所示,这就是unanchored的内容。

scala> val part = """TEXT:123:4:5"""
part: String = TEXT:123:4:5

scala> val part2 = """ text="TEXT:123:4:1">"""
part2: String = " text="TEXT:123:4:1">"

scala> val regex = """TEXT:(\d+):(\d+):(\d+)""".r.unanchored
regex: scala.util.matching.UnanchoredRegex = TEXT:(\d+):(\d+):(\d+)

scala> def matchAndPrint(text: String) {
     |   println(text match {
     |     case regex(num1, num2, num3) => s"$num1:$num2:$num3"
     |     case _ => "no match"
     |   })
     | }
matchAndPrint: (text: String)Unit

scala> matchAndPrint(part)
123:4:5

scala> matchAndPrint(part2)
123:4:1

Sorry I couldn't find a canonical Q&A. 对不起,我找不到规范的问答。 It has come up several times. 它出现了好几次。

Regex matching requires that it match the full string, so the text before and after the relevant portion in part2 is causing you the problem. 正则表达式匹配要求其完整的字符串匹配,所以之前并在相关部分之后的文本part2是造成你的问题。

Try this: 尝试这个:

val regex = """.*TEXT:(\d+):(\d+):(\d+).*""".r

""" text="TEXT:123:4:1">""" match {
  case regex(num1, num2, num3) => s"$num1:$num2:$num3"
}

// res0: String = 123:4:1

You are trying to do a complete match. 你正在努力做一个完整的比赛。

You therefore need to allow for the characters at the start and end of part2 , for example: 因此,您需要允许part2开头和结尾的字符,例如:

val regex = """.*TEXT:(\d+):(\d+):(\d+).*""".r

(Just adding .* at the start and end of the regex, to match anything) (只需在正则表达式的开头和结尾添加.*以匹配任何内容)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM