关于捕获组的java正则表达式问题

标签 java regex

public void test(){
    String source = "hello<a>goodA</a>boys can <a href=\"www.baidu.com\">goodB</a>\"\n"
                + "                + \"this can help";
    Pattern pattern = Pattern.compile("<a[\\s+.*?>|>](.*?)</a>");
    Matcher matcher = pattern.matcher(source);
    while (matcher.find()){
        System.out.println("laozhu:" + matcher.group(1));
    }
}

输出:

laozhu:goodA
laozhu:href="www.baidu.com">goodB

为什么第二个匹配不是laozhu:goodB

最佳答案

试试这个正则表达式:

<a(?: .*?)?>(\w+)<\/a>

所以你的Pattern应该是这样的:

Pattern pattern = Pattern.compile("<a(?: .*?)?>(\\w+)<\\/a>");

它匹配 goodAgoodB

详细说明请看这里:Regex101 .

关于关于捕获组的java正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35911482/

相关文章:

java和nlp提取信息(恶意软件名称)和过滤

java - Java 中模式匹配的困惑

regex - Linux '' 查找 '' command: File aging for special extention. Regex and mtime doesn' t 一起工作

regex - 使用正则表达式验证 ASP Classic 中的表单和查询字符串。几乎可以工作但缺少一些东西?

java - 如何制作方法 getUserById

java - 从 hashmap 对象中删除值的有效方法

java - 从网络应用程序停止/重启计算机的功能

java - 如何使用正则表达式删除电子邮件地址中的点 (.) 字符

c# - 正则表达式获取我的文件的父目录在字符串文件路径中

java - 在 Rally 中,如何使用 Web 服务 v2.0 获取具有属性类型的字段列表