How to test if Scala combinator parser matches a string
- by W.P. McNeill
I have a Scala combinator parser that handles comma-delimited lists of decimal numbers.
object NumberListParser extends RegexParsers {
def number: Parser[Double] = """\d+(\.\d*)?""".r ^^ (_.toDouble)
def numbers: Parser[List[Double]] = rep1sep(number, ",")
def itMatches(s: String): Boolean = parseAll(numbers, s) match {
case _: Success[_] => true
case _ => false
}
}
The itMatches function returns true when given a string that matches the pattern. For example:
NumberListParser.itMatches("12.4,3.141") // returns true
NumberListParser.itMatches("bogus") // returns false
Is there a more terse way to do this? I couldn't find one in the documentation, but my function sees a bit verbose, so I wonder if I'm overlooking something.