简体   繁体   English

Scala是否等同于“匹配”正则表达式方法?

[英]Scala equivalent for 'matches' regex method?

Struggling with my first (ever) Scala regex here. 在这里与我的第一个(有史以来)Scala正则表达式作斗争。 I need to see if a given String matches the regex: " animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+> ". 我需要查看给定的字符串是否与正则表达式匹配:“ animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+> ”。

So, some examples: 因此,一些示例:

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.

My best attempt so far: 到目前为止,我最大的尝试是:

val animalRegex = "animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
animalRegex.findFirstIn("animal<fizz,buzz")

Unfortunately that's where I'm hitting a brick wall. 不幸的是,那是我碰到砖墙的地方。 findFirstIn and all the other obvious methods available of animalRegex all return Option[String] types. findFirstInanimalRegex提供的所有其他显而易见的方法都返回Option[String]类型。 I was hoping to find something that returns a boolean, so something like: 我希望找到一些返回布尔值的东西,例如:

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(...)
}

So I need the equivalent of Java's matches method, and then need a way to access the "left operand" (that is, the value of the first [a-zA-Z0-9]+ group, which in the current case is " fizz "), and then ditto for the right/second operand (" buzz "). 因此,我需要一个等效的Java的matches方法,然后需要一种方法来访问“左操作数”(即,第一个[a-zA-Z0-9]+组的值,在当前情况下为“ fizz “),然后右移/右移第二个操作数(” buzz “)。 Any ideas where I'm going awry? 有什么想法我要去哪里吗?

To be able to extract the matched parts from your string, you'll need to add capture groups to your regex expression, like so (note the parentheses): 为了能够从字符串中提取匹配的部分,您需要将捕获组添加到正则表达式中,如下所示(请注意括号):

val animalRegex = "animal<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r

Then, you can use Scala's pattern matching to check for a match and extract the operands from the string: 然后,您可以使用Scala的模式匹配来检查匹配项并从字符串中提取操作数:

val str = "animal<fizz,3d>"
val result = str match {
    case animalRegex(op1,op2) => s"$op1, $op2"
    case _                    => "Did not match"
}

In this example, result will contain "fizz, 3d" 在此示例中, result将包含"fizz, 3d"

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

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