java - GWT RegExp - 多个匹配

标签 java regex gwt jsoup

我想找到输入字符串中的所有“代码”匹配项(使用 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/

相关文章:

java - Netbeans 未使用 JDK 1.8.0_40 启动 Java DB 服务器

javascript - 电话号码验证正则表达式由一个加号开始和前面的数字组成

python - 45 个十六进制数字或 48 个十六进制数字的模式的正则表达式 - Python

python - 子字符串在字符串中的位置

java - XML序列化只序列化一个字段

java - 更改 android 中字符串数组内的字体样式/格式

javascript - MGWT ScrollPanel.scrollTo(0, y) 导致无法读取未定义的属性 'style'

java - GWT - 如何构建一棵动态地从服务器带来儿子的树?

java - 绘制图形节点的坐标算法

java - GWT - 货币格式化程序安全客户端和服务器端