java正则匹配URL
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String url = "http://192.168.0.1:8080/index.html";
// 定义 IP 地址和端口号的正则表达式
String ipRegex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
String portRegex = "(\\d{1,5})";
// 构建完整的 URL 正则表达式
String urlRegex = "^(http|https)://" + ipRegex + ":" + portRegex + "/.*$";
// 编译正则表达式
Pattern pattern = Pattern.compile(urlRegex);
// 创建 Matcher 对象
Matcher matcher = pattern.matcher(url);
// 进行匹配
if (matcher.matches()) {
// 提取 IP 地址和端口号
String ipAddress = matcher.group(1);
String port = matcher.group(2);
System.out.println("IP 地址: " + ipAddress);
System.out.println("端口号: " + port);
}
}
}
匹配域名或IP地址正则(待验证)
^(http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?|^((http:\/\/|https:\/\/)?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:\d{0,5})?(\/.*)?$