1

我正在尝试通过一些没有分隔符(如空格)的关键字来拆分输入。

object MyParser extends JavaTokenParsers {
  def expr = (text | keyword).+
  def text = ".+".r ^^ ("'"+_+"'")
  def keyword = "ID".r ^^ ("["+_+"]")
}

val p = MyParser
p.parse(p.expr, "fooIDbar") match {
  case p.Success(r, _) => r foreach print
  case x => println(x.toString)
}

这输出如下。

>> 'hogeIDfuga'

但我真正想做的就是这样。

>> 'hoge'[ID]'fuga'


它似乎text吞噬了所有的角色。我试图表达 [text不包含keyword],但我不能。如何在正则表达式或 Scala 解析器中表达它?或任何其他解决方案?

我看过一些帖子1 2,但在我的情况下它们不起作用。

4

1 回答 1

3

First, keyword is a constant word so you don't need a regex, a plain string is enough. Second, a text is some string that doesn't contain a keyword, not any string. Try this:

import util.parsing.combinator._

object MyParser extends JavaTokenParsers {
  def expr = (text | keyword).+
  def text = """((?!ID).)+""".r ^^ ("'"+_+"'")
  def keyword = "ID" ^^ ("["+_+"]")
}

val p = MyParser
p.parse(p.expr, "fooIDbar") match {
  case p.Success(r, _) => r foreach print
  case x => println(x.toString)
}

As for the trick of writing a regex that not matching something, read this.

于 2012-07-14T01:31:32.767 回答