Java正则表达式匹配与替换全解析
1. 匹配结果示例
以下是一个展示众多匹配结果方法的示例。给定一个字符串形式的URL,代码会识别并报告该URL的协议( http 或 https )、主机名以及可选的端口号:
String url = "http://regex.info/blog";
String regex = "(?x)^(https?):// ([^/:]+) (?:(\\d+))?";
Matcher m = Pattern.compile(regex).matcher(url);
if (m.find()) {
System.out.print(
"Overall [" + m.group() + "]" +
" (from "
+ m.start() + " to " + m.end() + ")\n" +
"Protocol [" + m.group(1) + "]" +
" (from "
+ m.start(1) + " to " + m.end(1) + ")\n" +
"Hostname [" + m.group(2) + "]" +
" (from "
+ m.start(2) + " to " + m.end(2) + ")\n"
);
// 组 #3 可能未参与匹配,因此这里需要小心处理
if (m.group(3) == null)
System.out.pri
超级会员免费看
订阅专栏 解锁全文
2168

被折叠的 条评论
为什么被折叠?



