[英]Scala equivalent for 'matches' regex method?
在这里与我的第一个(有史以来)Scala正则表达式作斗争。 我需要查看给定的字符串是否与正则表达式匹配:“ animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>
”。
因此,一些示例:
animal<0,sega> => valid
animal<fizz,buzz> => valid
animAl<fizz,buzz> => illegal; animAl contains upper-case (and this is case-sensitive)
animal<fizz,3d> => valid
animal<,3d> => illegal; there needs to be something [a-zA-Z0-9]+ between '<' and ','
animal<fizz,> => illegal; there needs to be something [a-zA-Z0-9]+ between ',' and '>'
animal<fizz,%> => illegal; '%' doesn't match [a-zA-Z0-9]+
etc.
到目前为止,我最大的尝试是:
val animalRegex = "animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
animalRegex.findFirstIn("animal<fizz,buzz")
不幸的是,那是我碰到砖墙的地方。 findFirstIn
和animalRegex
提供的所有其他显而易见的方法都返回Option[String]
类型。 我希望找到一些返回布尔值的东西,例如:
val animalRegex = "animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
if(animalRegex.matches("animal<fizz,buzz>")) {
val leftOperand : String = getLeftOperandSomehow(...)
val rightOperand : String = getRightOperandSomehow(...)
}
因此,我需要一个等效的Java的matches
方法,然后需要一种方法来访问“左操作数”(即,第一个[a-zA-Z0-9]+
组的值,在当前情况下为“ fizz
“),然后右移/右移第二个操作数(” buzz
“)。 有什么想法我要去哪里吗?
为了能够从字符串中提取匹配的部分,您需要将捕获组添加到正则表达式中,如下所示(请注意括号):
val animalRegex = "animal<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r
然后,您可以使用Scala的模式匹配来检查匹配项并从字符串中提取操作数:
val str = "animal<fizz,3d>"
val result = str match {
case animalRegex(op1,op2) => s"$op1, $op2"
case _ => "Did not match"
}
在此示例中, result
将包含"fizz, 3d"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.