【问题标题】:Parsing wikiText with regex in Java在 Java 中使用正则表达式解析 wikiText
【发布时间】:2011-06-03 13:27:40
【问题描述】:

给定一个 wikiText 字符串,例如:

{{ValueDescription
    |key=highway
    |value=secondary
    |image=Image:Meyenburg-L134.jpg
    |description=A highway linking large towns.
    |onNode=no
    |onWay=yes
    |onArea=no
    |combination=
    * {{Tag|name}}
    * {{Tag|ref}}
    |implies=
    * {{Tag|motorcar||yes}}
    }}

我想在 Java/Groovy 中解析模板 ValueDescriptionTag。 我尝试使用正则表达式/\{\{\s*Tag(.+)\}\}/,它很好(它返回|name|ref|motorcar||yes),但是 /\{\{\s*ValueDescription(.+)\}\}/ 不起作用(它应该返回上面的所有文本)。

预期输出

有没有办法跳过正则表达式中的嵌套模板?

理想情况下,我宁愿使用简单的 wikiText 2 xml 工具,但我找不到类似的工具。

谢谢! 木龙

【问题讨论】:

  • 您能否提供一些您期望从上述输入中得到的示例输出?

标签: java regex mediawiki wikitext


【解决方案1】:

任意嵌套的标签将不起作用,因为这使得语法 non-regular。您需要能够处理上下文无关语法的东西。 ANTLR 是一个不错的选择。

【讨论】:

    【解决方案2】:

    使用Pattern.DOTALL 选项创建您的正则表达式模式,如下所示:

    Pattern p = Pattern.compile("\\{\\{\\s*ValueDescription(.+)\\}\\}", Pattern.DOTALL);
    

    示例代码:

    Pattern p=Pattern.compile("\\{\\{\\s*ValueDescription(.+)\\}\\}",Pattern.DOTALL);
    Matcher m=p.matcher(str);
    while (m.find())
       System.out.println("Matched: [" + m.group(1) + ']');
    

    输出

    Matched: [
    |key=highway
    |value=secondary
    |image=Image:Meyenburg-L134.jpg
    |description=A highway linking large towns.
    |onNode=no
    |onWay=yes
    |onArea=no
    |combination=
    * {{Tag|name}}
    * {{Tag|ref}}
    |implies=
    * {{Tag|motorcar||yes}}
    ]
    

    更新

    假设关闭}} 出现在{{ValueDescription 的单独行上,以下模式将用于捕获多个ValueDescription

    Pattern p = Pattern.compile("\\{\\{\\s*ValueDescription(.+?)\n\\}\\}", Pattern.DOTALL);
    

    【讨论】:

    • 这可行,但如果有另一个 '''{{ValueDescription''' 块它不会停止。
    • @Mulone:假设关闭 }} 出现在 {{ValueDescription 的单独行上,以下模式将用于捕获多个 ValueDescriptionPattern p = Pattern.compile("\\{\\{\\s*ValueDescription(.+?)\n\\}\\}", Pattern.DOTALL);
    • 我认为这个假设在阅读 wikitext 时是不成立的。有没有办法让它变得健壮?
    • @Mulone:正则表达式在这里确实有限制,你需要有某种类型的模式来匹配。结束 }} 必须要么在单独的行上,要么后面跟着我们可以在上面的模式中使用的其他字符。为了验证/匹配非常规文本,您最终需要一个解析器实用程序,或者需要编写自己的解析器。
    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2010-11-22
    相关资源
    最近更新 更多