【问题标题】:Scala equivalent for 'matches' regex method?“匹配”正则表达式方法的Scala等价物?
【发布时间】:2016-09-29 19:54:01
【问题描述】:

在这里与我的第一个(曾经的)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")

不幸的是,这就是我碰壁的地方。 findFirstInanimalRegex 的所有其他明显可用的方法都返回 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]+组的值,在当前情况下为“@987654330 @"),然后是右/第二个操作数 ("buzz")。有什么想法会出错吗?

【问题讨论】:

    标签: regex scala


    【解决方案1】:

    为了能够从您的字符串中提取匹配的部分,您需要将捕获组添加到您的正则表达式中,如下所示(注意括号):

    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"

    【讨论】:

    • 多么美丽的答案。我不知道他们为什么不提供matches,但scaladoc 说A regular expression is used to determine whether a string matches a pattern and, if it does, to extract or transform the parts that match. 如果你只想检查它是否匹配,则忽略组,成语是case animalRegex(_*) =&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2010-10-08
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多