Accessing Scala Parser regular expression match data

前端 未结 4 1317
孤街浪徒
孤街浪徒 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:16

    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:

    package scalucene.query
    
    import scala.util.matching.Regex
    import scala.util.parsing.combinator._
    
    object QueryParser extends RegexParsers {
      override def skipWhitespace = false
    
      private def quoted = regex(new Regex("\"[^\"]+"))
      private def colon = regex(new Regex(":"))
      private def word = regex(new Regex("\\w+"))
      private def fielded = (regex(new Regex("[^:]+")) <~ colon) ~ word
      private def term = (fielded | word | quoted)
    
      def parseItem(str: String) = parse(term, str)
    }
    

    It seems that you can grab the matched groups after parsing like this:

    QueryParser.parseItem("nameExample:valueExample") match {
      case QueryParser.Success(result:scala.util.parsing.combinator.Parsers$$tilde, _) => {
          println("Name: " + result.productElement(0) + " value: " + result.productElement(1))
      }
    }
    

提交回复
热议问题