在 Java 中,可以使用 java.util.regex 包里的 正则表达式(Regex) 来匹配网址(URL)。下面从简单匹配到较严谨匹配逐步说明。
如果你只是想判断字符串里是否包含 http/https 开头的网址:
String regex = "https?://\\S+";
示例:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String text = "访问 https://www.example.com 查看详情";
String regex = "https?://\\S+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}
}
输出:
https://www.example.com
✅ 适合:日志提取、简单文本处理
String regex = "https?://[\\w.-]+(:\\d+)?(/[\\w./?%&=#-]*)?";
说明:
https?:http 或 https[\\w.-]+:域名(:\\d+)?:可选端口(/...)?:可选路径和参数如果你要验证一个完整 URL 是否合法,更推荐不用正则,而用:
import java.net.URL;
public class Test {
public static void main(String[] args) {
String url = "https://www.example.com/path?x=1";
try {
new URL(url);
System.out.println("合法 URL");
} catch (Exception e) {
System.out.println("非法 URL");
}
}
}
✅ 优点:标准、可靠、少踩坑
String regex = "(https?://[\\w.-]+(:\\d+)?(/[\\w./?%&=#-]*)?)";
\ 要写成 \\| 场景 | 建议 |
|---|---|
| 提取文本中的网址 | 正则 https?://\S+ |
| 验证 URL 合法性 | java.net.URL |
| 严格规范匹配 | 专用 URL 正则或库 |
如果你有具体需求(比如只匹配域名、只匹配内网地址、限制后缀),可以告诉我,我帮你写精确正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。