How to test if Scala combinator parser matches a string
Posted
by
W.P. McNeill
on Stack Overflow
See other posts from Stack Overflow
or by W.P. McNeill
Published on 2012-12-13T05:00:38Z
Indexed on
2012/12/13
5:03 UTC
Read the original article
Hit count: 126
scala
|parser-combinators
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.
© Stack Overflow or respective owner