如何限制Regex和Parser组合器中的nestead标记?

时间:2011-12-04 02:26:09

标签: regex parsing scala parser-combinators

我想实现一个简单的类似Wiki的标记解析器,作为使用Scala解析器组合器的练习。

我想逐点解决这个问题,所以这是我想在第一个版本中实现的:一个简单的内联文字标记。

例如,如果输入字符串是:

This is a sytax test ``code here`` . Hello ``World``

输出字符串应为:

This is a sytax test <code>code here</code> . Hello <code>World</code>

我尝试使用RegexParsers来解决这个问题,这就是我现在所做的:

import scala.util.parsing.combinator._
import scala.util.parsing.input._

object TestParser extends RegexParsers
{   
    override val skipWhitespace = false

    def toHTML(s: String) = "<code>" + s.drop(2).dropRight(2) + "</code>"

    val words = """(.)""".r
    val literal = """\B``(.)*``\B""".r ^^ toHTML

    val markup = (literal | words)*

    def run(s: String) = parseAll(markup, s) match {
        case Success(xs, next) => xs.mkString
        case _ => "fail"
    }
}

println (TestParser.run("This is a sytax test ``code here`` . Hello ``World``"))

在此代码中,只包含一个<code>标记的更简单输入正常工作,例如:

This is a sytax test ``code here``.

成为

This is a sytax test <code>code here</code>.

但是当我用上面的例子运行它时,它会产生

This is a sytax test <code>code here`` . Hello ``World</code>

我认为这是因为我使用的正则表达式:

"""\B``(.)*``\B""".r

允许``对中的任何字符。

我想知道我是否应该限制无法嵌套``并解决此问题?

3 个答案:

答案 0 :(得分:2)

以下是关于非贪婪匹配的一些文档:

http://www.exampledepot.com/egs/java.util.regex/Greedy.html

基本上它从第一个`开始,并尽可能地得到一个匹配,匹配世界末尾的``。

通过投入?在你的*之后,你告诉它尽可能做最短的比赛,而不是最长的比赛。

另一个选择是使用[^`] *(除了`之外的任何东西),这将迫使它提前停止。

答案 1 :(得分:0)

经过一些反复试验后,我发现以下正则表达式似乎有效:

"""``(.)*?``"""

答案 2 :(得分:0)

我对正则表达式解析器知之甚少,但您可以使用简单的1-liner:

def addTags(s: String) =
  """(``.*?``)""".r replaceAllIn (
                    s, m => "<code>" + m.group(0).replace("``", "") + "</code>")

测试:

scala> addTags("This is a sytax test ``code here`` . Hello ``World``")
res0: String = This is a sytax test <code>code here</code> . Hello <code>World</code>
相关问题