I wondering if it's possible to get the MatchData generated from the matching regular expression in the grammar below.
object DateParser extends JavaTokenParsers {
....
val dateLiteral = """(\d{4}[-/])?(\d\d[-/])?(\d\d)""".r ^^ {
... get MatchData
}
}
One option of course is to perform the match again inside the block, but since the RegexParser has already performed the match I'm hoping that it passes the MatchData to the block, or stores it?
When a Regex is used in a RegexParsers instance, the implicit def regex(Regex): Parser[String] in RegexParsers is used to appoly that Regex to the input. The Match instance yielded upon successful application of the RE at the current input is used to construct a Success in the regex() method, but only its "end" value is used, so any captured sub-matches are discarded by the time that method returns.
As it stands (in the 2.7 source I looked at), you're out of luck, I believe.
Here is the implicit definition that converts your
Regex
into aParser
:Just adapt it:
Example:
I ran into a similar issue using scala 2.8.1 and trying to parse input of the form "name:value" using the
RegexParsers
class:It seems that you can grab the matched groups after parsing like this:
No, you can't do this. If you look at the definition of the Parser used when you convert a regex to a Parser, it throws away all context and just returns the full matched string:
http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_7_final/src/library/scala/util/parsing/combinator/RegexParsers.scala?view=markup#L55
You have a couple of other options, though:
The first would look like
The
<~
means "require these two tokens together, but only give me the result of the first one.The
~
means "require these two tokens together and tie them together in a pattern-matchable ~ object.The
?
means that the parser is optional and will return an Option.The
.getOrElse
bit provides a default value for when the parser didn't define a value.