我有这样的正则表达式:
val myregex = "This is a (.*) text for (.*) and other thing like .*".r
如果我跑:
> val myregex(a,b) = "This is a test text for something and other thing like blah blah"
a: String = test
b: String = something
没关系,失败的是b
:
> val myregex(a,b) = "This is a test text for and other thing like blah blah"
scala.MatchError: This is a test text for and other thing like blah blah (of class java.lang.String)
... 33 elided
有没有办法保留价值a
并将b
替换为后备值(反之亦然)?或者唯一的解决方案是将正则表达式分成两个区别的正则表达式?
答案 0 :(得分:2)
您的原始正则表达式需要for
和and
之间连续2个空格。
您可以通过使用非捕获组包装空格和后续(.*)
模式来更改正则表达式以使字符串与可选模式实际匹配,并应用{{1}量词使它成为可选:
?
请参阅online Scala demo。这里有匹配,但是val myregex = "This is a (.*) text for(?: (.*))? and other thing like .*".r
val x = "This is a test text for and other thing like blah blah"
x match {
case myregex(a, b) => print(s"${a} -- ${b}");
case _ => print("none")
}
// => test -- null
只是空,因为第二个捕获组没有参与匹配(并且没有初始化)。
答案 1 :(得分:0)
或唯一的解决方案是将正则表达式分为两个区分正则表达式?
这是唯一的解决方案。你最好的选择可能是使用模式匹配:
("This is a test text for something", "and other thing like blah blah") match {
case (r1(a), r2(b)) => (a, b)
case (r1(a), _) => (a, "fallback")
}