Java正则表达式匹配与替换全解析
1. 匹配结果示例
在Java中,我们可以使用正则表达式来解析URL,识别其协议、主机名和可选端口号。以下是一个示例代码:
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"
);
if (m.group(3) == null)
System.out.println("No port; default of ’80’ is assumed");
else {
System.out.print("Port