Accessing Scala Parser regular expression match data

前端 未结 4 1378
孤街浪徒
孤街浪徒 2021-02-08 07:55

I wondering if it\'s possible to get the MatchData generated from the matching regular expression in the grammar below.

object DateParser extends JavaTokenParser         


        
4条回答
  •  广开言路
    2021-02-08 08:19

    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:

    • break up your parser into several smaller parsers (for the tokens you actually want to extract)
    • define a custom parser that extracts the values you want and returns a domain object instead of a string

    The first would look like

    val separator = "-" | "/"
      val year = ("""\d{4}"""r) <~ separator
      val month = ("""\d\d"""r) <~ separator
      val day = """\d\d"""r
    
      val date = ((year?) ~ (month?) ~ day) map {
        case year ~ month ~ day =>
          (year.getOrElse("2009"), month.getOrElse("11"), day)
      }
    

    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.

提交回复
热议问题