15

我正在尝试使用以下代码匹配 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>

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

4

2 回答 2

24

如果不匹配,可选组将为 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>
于 2010-03-17T12:00:38.213 回答
0

我认为您的正则表达式没有任何问题。尽管您不需要.在 char 类中转义。

编辑:

您可以尝试以下方法:

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

捕获名称和值,其中值可以具有可选符号。

于 2010-03-17T10:41:10.713 回答