Java正则表达式模式获取 anchor 文本

标签 java html regex

我有一个页面源,我想获取其所有 anchor 标记的 anchor 文本

有人可以帮我设计一下它的模式吗?

提前致谢

最佳答案

karim79 是对的,正则表达式可能是错误的方式,但无论如何,这里有一种可以在 Java 中完成的简单方法。请注意,如果 anchor 在 href 之前具有其他属性,则这将不起作用。不过,这可能是一个好的开始,或者可以帮助您了解如何做到这一点。

    String html = "<body>" +
            "<a href=\"#first\">got to first</a>" +
            "<span>something else</span>" +
            "<a href=\"#second\">got to second</a>" +
            "</body>";

    Pattern pattern = Pattern.compile("<a href=\"#(\\w+)\">([\\w\\s]+)</a>");
    Matcher matcher = pattern.matcher(html);
    while(matcher.find()){
        System.out.println(matcher.group(2));
    }

关于Java正则表达式模式获取 anchor 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3776939/

相关文章:

Windows 中的 java.io.IOException : The process cannot access the file because another process has locked a portion - when using IOUtils. copyLarge()

java - 循环不工作,为什么会这样?

javascript - 如何使用 angularjs 获取用户所属的安全组列表

javascript - 如何选择父函数的$this?

python - 使用 Python 根据引用键从 bibtex 文件中删除特定条目

java - 通过 JsonPath 中的正则表达式过滤值

java - Apache Camel : Quotes will break the URI

java - com.google.gson.stream.MalformedJsonException

css - Bootstrap 下拉列表 "across"div

Javascript 替换正则表达式不起作用