在 Java 中,可以使用 正则表达式 配合 Pattern 和 Matcher 来提取文本中的网址链接。下面给你几种常见、实用的做法。
import java.util.regex.*;
import java.util.*;
public class UrlExtractor {
public static void main(String[] args) {
String text = "访问我的网站 https://www.example.com 和 http://test.com/index.html";
String regex = "https?://[\\w.-]+(?:\\.[\\w.-]+)+[\\w.,@?^=%&:/~+#-]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
https://www.example.com
http://test.com/index.html
https?://
http 或 https[\\w.-]+
(?:\\.[\\w.-]+)+
.com、.cn、.co.uk 等)[\\w.,@?^=%&:/~+#-]*
Set<String> urls = new HashSet<>();
while (matcher.find()) {
urls.add(matcher.group());
}
String regex = "(https?|ftp|file)://[\\w.-]+(?:\\.[\\w.-]+)+[\\w.,@?^=%&:/~+#-]*";
URL 规范非常复杂,正则只能“近似匹配”。
✅ 不要自己写正则解析 HTML
✅ 推荐用:
Document doc = Jsoup.parse(html);
Elements links = doc.select("a[href]");
for (Element link : links) {
System.out.println(link.attr("href"));
}
| 场景 | 建议 |
|---|---|
| 普通文本 | 正则提取 |
| 简单需求 | https?://... |
| HTML 页面 | Jsoup |
| 高准确性 | 正则 + URL 校验 |
如果你有具体文本样例(比如微信文章、HTML、日志),我可以帮你写一个更精准的正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。