3 回答
TA贡献1772条经验 获得超6个赞
干得好 :
Pattern pattern = Pattern.compile("^(?:(?:http)s?://)?(?<hostGroup>[^/:]+).*");
Matcher matcher = pattern.matcher("https://stackoverflow.com/questions/");
if (matcher.matches()) {
System.out.println(matcher.group("hostGroup"));
} else {
System.out.println("Not found! Invalid URL ^^");
}
上面将找到stackoverflow.com的以下 url 字符串:
https://stackoverflow.com/questions/
http://stackoverflow.com/questions/
stackoverflow.com/questions/
stackoverflow.com:80/questions/
stackoverflow.com/
stackoverflow.com
我想那是为了练习正则表达式?否则,尽可能使用标准 API -(根据您的情况URI#getHost()
!)
干杯!
TA贡献1776条经验 获得超12个赞
如果您可以将 URL 放入字符串中,则有以下选项:
public static void main(String []args){
String str ="https://stackoverflow.com/questions/";
String[] parts = str.split("/");
String part1 = parts[0]; //https:
String part2 = parts[1]; //'nothing'
String part3 = parts[2]; //stackoverflow.com
String part4 = parts[3]; //questions
}
添加回答
举报