我想找到输入字符串中的所有“代码”匹配项(使用 GWT RegExp)。当我调用“regExp.exec(inputStr)”方法时,它只返回第一个匹配项,即使我多次调用它:
String input = "ff <code>myCode</code> ff <code>myCode2</code> dd <code>myCode3</code>";
String patternStr = "<code[^>]*>(.+?)</code\\s*>";
// Compile and use regular expression
RegExp regExp = RegExp.compile(patternStr);
MatchResult matcher = regExp.exec(inputStr);
boolean matchFound = (matcher != null); // equivalent to regExp.test(inputStr);
if (matchFound) {
// Get all groups for this match
for (int i=0; i<matcher.getGroupCount(); i++) {
String groupStr = matcher.getGroup(i);
System.out.println(groupStr);
}
}
如何获得所有匹配项?
编辑: 就像greedybuddha 指出的那样:正则表达式并不真正适合解析(X)HTML。我尝试了一下 JSOUP,它比使用正则表达式方便得多。我的 jsoup 代码现在看起来像这样。我正在重命名所有代码标签并将它们应用到 CSS 类:
String input = "ff<code>myCode</code>ff<code>myCode2</code>";
Document doc = Jsoup.parse(input, "UTF-8");
Elements links = doc.select("code"); // a with href
for(Element link : links){
System.out.println(link.html());
link.tagName("pre");
link.addClass("prettify");
}
System.out.println(doc);
最佳答案
使用“g”编译正则表达式flag ,用于全局匹配。
RegExp regExp = RegExp.compile(patternStr,"g");
我认为您还需要“m”进行多行匹配,“gm”
。
话虽如此,对于 HTML/XML 解析,您应该考虑使用 JSoup 或其他替代方案。
关于java - GWT RegExp - 多个匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000192/