斯卡拉:匹配的可选正则表达式组

问题描述:

我想匹配在斯卡拉2.8(测试版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> 

但是,这是行不通的。匹配可选正则表达式组的正确方法是什么?

可选组将是空,如果不匹配,所以你需要在模式匹配包括“空”:

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

Scala在Regex.unapplySeq中使用Matcher.group方法。这指定如果某个组未能匹配部分序列,则返回null - 2010-03-17 12:25:15

+2

这将是很好,如果斯卡拉可以使用一个可选的正则表达式字段选项类,而不是要求空检查。 – 2014-11-07 11:24:16

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

编辑:

你可以尝试这样的:

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

捕捉到货物的价值可以有一个可选的符号的名称和值。

+0

@codaddict感谢指出了这一点;)的正则表达式是好的,问题是我无法看到谁使用Scala模式匹配系统匹配可选组。我可以在网上找到没有例子这样做 – 2010-03-17 10:43:18

+0

@codaaddict谢谢,这将让我的代码工作,但斯卡拉模式匹配问题仍然存在:)我实际上需要不同的XML根据是否有或不是符号,所以使用模式匹配系统来提取和测试是否有迹象似乎是对我来说最干净的解决方案 – 2010-03-17 11:04:47