正则表达式 练习:解析URL
Jihongchang(讨论 | 贡献)2022年11月22日 (二) 08:20的版本
https://www.bilibili.com/video/BV1Eq4y1E79W?p=26
对一个URL进行解析 "https://www.sohu.com:8080/abc/index.html"
- 要求得到协议是什么? http
- 域名是什么? www.sohu.com
- 端口是什么? 8080
- 文件名是什么? index.htm
自己实现
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Homework03 {
public static void main(String[] args) {
String content = "https://www.sohu.com:8080/abc/index.html";
String regex = "^(http[s]?)://((\\w+\\.)+\\w+):(\\d+)(/\\w+)+/(\\w+\\.\\w+)$";
Matcher matcher = Pattern.compile(regex).matcher(content);
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(4));
System.out.println(matcher.group(6));
}
}
}
https
www.sohu.com
8080
index.html