任务是匹配表达式中的逗号分隔符,排除情况,当数字或空格后面有逗号时。
对于此类测试用例,正则表达式必须匹配逗号:
"a,b"
"a,b,c"
"a,b,c,d"
"a,b,c,d,e1,1"
对于这样的:
"ab"
"abc1,1"
一定不能匹配。
一般用逗号分隔的元素个数可以是8-10个。
Scala 代码上的正则表达式是
private val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*\\D\\s*,.*$""".r
特别是
^.*\\D\\s*,.*$
工作正常。例如,我签入了该服务https://regex101.com
但是我的带有模式匹配的 Scala 代码不起作用。
address match {
case ContainCommaSeparatorExcludingDigitBeforeComma(_, _, _) => print("found")
case _ => print("not found")
}
我做错了什么?
ContainCommaSeparatorExcludingDigitBeforeComma(_, _, _)
替换为 ContainCommaSeparatorExcludingDigitBeforeComma()
,因为没有定义组,因此无需解构。object Main extends App {
val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*\D\s*,.*$""".r
val inputs = List("a,b", "a,b,c", "a,b,c,d", "a,b,c,d,e1,1", "ab", "abc1,1")
inputs.foreach { input =>
input match {
case ContainCommaSeparatorExcludingDigitBeforeComma() => println("found")
case _ => println("not found")
}
}
}
还有一个包含组和模式匹配的示例(如果这就是您想要的)(1 组,提取
\D
)
object Main extends App {
val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*(\D)\s*,.*$""".r
val inputs = List("a,b", "a,b,c", "a,b,c,d", "a,b,c,d,e1,1", "ab", "abc1,1")
inputs.foreach { input =>
input match {
case ContainCommaSeparatorExcludingDigitBeforeComma(m) => println(s"found '$m'")
case _ => println("not found")
}
}
}