在 Java 中,可以使用 正则表达式(Regular Expression) 配合 java.util.regex 包来从文本中抓取网址(URL)。下面从简单示例到常见注意点给你说明。
import java.util.regex.*;
import java.util.*;
public class UrlExtractor {
public static void main(String[] args) {
String text = "访问 https://www.baidu.com 和 http://example.com/index.html 查看内容";
// 正则:匹配 http 或 https 开头的网址
String regex = "https?://[\\w./?=&#%-]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
https://www.baidu.com
http://example.com/index.html
如果你希望匹配更标准的网址(包含域名、端口、路径等):
String regex =
"https?://[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:/~+#-]*)";
a.b.c.com)String regex = "https?://[\\w.-]+";
示例输出:
https://www.baidu.com
http://example.com
如果你还想匹配 www.baidu.com 这种:
String regex = "(https?://)?[\\w-]+(\\.[\\w-]+)+";
List<String> urls = Pattern.compile("https?://[\\w./?=&#%-]+")
.matcher(text)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
正则不适合完全解析 URL
new URI(url)
或
URL url = new URL(str);
HTML 中抓 URL
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
| 场景 | 建议 |
|---|---|
| 文本中提取网址 | 正则 ✅ |
| 校验 URL 是否合法 | URI / URL ✅ |
| 解析网页链接 | Jsoup ✅ |
| 高性能批量抓取 | 正则 + 流式处理 ✅ |
如果你有具体文本样例(比如日志、HTML、微信文本),我可以帮你写精准正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。