Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Matching optional Regular Expression groups

I'm trying to match on an option group in Scala 2.8 (beta 1) with the following code:

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>

But this is not working. What is the correct way to match optional regex groups?

like image 594
BefittingTheorem Avatar asked Mar 17 '10 10:03

BefittingTheorem


1 Answers

The optional group will be null if it is not matched so you need to include "null" in the pattern match:

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>
like image 184
BefittingTheorem Avatar answered Oct 06 '22 00:10

BefittingTheorem