给定一个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中的模板ValueDescription和Tag。我尝试使用regex /\{\{\s*Tag(.+)\}\}/,它很好(它返回|name、|ref和|motorcar||yes),但是/\{\{\s*ValueDescription(.+)\}\}/不能工作(它应该返回上面所有的文本)。
预期产出
有没有一种方法可以跳过regex中的嵌套模板?
理想情况下,我宁愿使用一个简单的wikiText 2 xml工具,但是我找不到类似的东西。
谢谢!木兰
发布于 2011-06-03 14:29:44
使用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);发布于 2011-06-03 13:31:45
任意嵌套的标记不能工作,因为这使得语法非常规。你需要一些能够处理上下文无关语法的东西。反是一个很好的选择。
https://stackoverflow.com/questions/6227706
复制相似问题