3 回答

TA貢獻1772條經(jīng)驗 獲得超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 -(根據(jù)您的情況URI#getHost()
?。?/p>
干杯!

TA貢獻1776條經(jīng)驗 獲得超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
}
添加回答
舉報