标签导航:

如何用正则表达式从html代码中提取特定类型的链接?

正则表达式提取特定内容

在使用正则表达式时,有时我们需要过滤出特定内容。本文将介绍如何使用正则表达式从 html 代码中提取含有特定字符的链接。

问题:

如何从以下 html 代码中提取所有以 "www." 开头并以 ".com" 或 ".cn" 结尾的链接?

<p>++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++</p>

答案:

import java.util.regex.matcher;
import java.util.regex.pattern;

public class linkextractor {

    public static void main(string[] args) {
        string html = "<a>www.baidu.com</a><a>www.qq.com</a><a>www.aaa.cn</a>www.eee.cn";
        string reg = "www.*?(com|cn)";

        matcher matcher = pattern.compile(reg, pattern.case_insensitive).matcher(html);
        while (matcher.find()) {
            system.out.println(matcher.group());
        }
    }
}

匹配结果:

www.baidu.com
www.qq.com
www.aaa.cn
www.eee.cn

解析:

  • .*?:匹配 0 个或更多字符,但尽可能少的字符。
  • (com|cn):匹配 "com" 或 "cn" 字符串,使用圆括号分组是为了捕获匹配内容。
  • pattern.case_insensitive:设置正则表达式匹配时忽略大小写。