Scala:匹配可选的正则表达式组

时间:2010-03-17 10:31:56

标签: regex pattern-matching scala-2.8

我正在尝试使用以下代码匹配Scala 2.8(beta 1)中的选项组:

import scala.xml._

val StatementPattern = """([\w\.]+)\s*:\s*([+-])?(\d+)""".r

def buildProperty(input: String): Node = input match {
    case StatementPattern(name, value) => <propertyWithoutSign />
    case StatementPattern(name, sign, value) => <propertyWithSign />
}

val withSign = "property.name: +10"
val withoutSign = "property.name: 10"

buildProperty(withSign)        // <propertyWithSign></propertyWithSign>
buildProperty(withoutSign)     // <propertyWithSign></propertyWithSign>

但这不起作用。匹配可选正则表达式组的正确方法是什么?

2 个答案:

答案 0 :(得分:20)

如果不匹配,则可选组将为null,因此您需要在模式匹配中包含“null”:

import scala.xml._

val StatementPattern = """([\w\.]+)\s*:\s*([+-])?(\d+)""".r

def buildProperty(input: String): Node = input match {
    case StatementPattern(name, null, value) => <propertyWithoutSign />
    case StatementPattern(name, sign, value) => <propertyWithSign />
}

val withSign = "property.name: +10"
val withoutSign = "property.name: 10"

buildProperty(withSign)        // <propertyWithSign></propertyWithSign>
buildProperty(withoutSign)     // <propertyWithSign></propertyWithSign>

答案 1 :(得分:0)

我发现你的正则表达式没有任何问题。虽然您无需转义char类中的.

编辑:

您可以尝试以下内容:

([\w.]+)\s*:\s*((?:+|-)?\d+)

捕获值可以有可选符号的名称和值。