java - 使用正则表达式模式验证域和子域的正则表达式是什么?
问题描述
我有一个域和子域列表,我正在检查该列表中的每个项目是否都是有效的域名(或子域),例如:www.google.com - google.com - drive.google.com。
这是我的正则表达式: ^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$
这是我的代码:
// Validate Domains
private boolean validateDomains (String domains) {
String domainsList[] = domains.split("\\n");
final Pattern domainPattern = Pattern.compile("^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$");
for (int i = 0; i < domainsList.length; i++) {
if (!domainPattern.matcher(domainsList[i]).matches()) {
return false;
}
}
return true;
}
此代码从未通过测试!
解决方案
或者,您可能会为您的表达式添加更多边界,类似于:
(?i)^(?:https?:\/\/)?(?:www\.)?(?:[a-z0-9-]+\.){1,9}[a-z]{2,5}(?:\/.*)?$
演示 1
或者
(?i)^(?:https?:\/\/)?(?:www\.)?(?:[a-z0-9-]{1,20}\.){1,9}[a-z]{2,5}(?:\/.*)?$
演示 2
测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class re{
public static void main(String[] args){
final String regex = "(?i)^(?:https?:\\/\\/)?(?:www\\.)?(?:[a-z0-9-]+\\.){1,9}[a-z]{2,5}(?:\\/.*)?$";
final String string = "www.google.com\n"
+ "google.com\n"
+ "drive.google.com\n"
+ "http://www.google.com\n"
+ "http://google.com\n"
+ "http://drive.google.com\n"
+ "https://www.google.com\n"
+ "https://www.google.com\n"
+ "https://www.drive.google.com\n"
+ "https://www.google.com/some_other_things\n"
+ "https://www.google.com/\n"
+ "https://www.drive.google.com/\n"
+ "https://www.a.a.a.a.a.a.a.a.a.google.com/";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
输出
Full match: www.google.com
Full match: google.com
Full match: drive.google.com
Full match: http://www.google.com
Full match: http://google.com
Full match: http://drive.google.com
Full match: https://www.google.com
Full match: https://www.google.com
Full match: https://www.drive.google.com
Full match: https://www.google.com/some_other_things
Full match: https://www.google.com/
Full match: https://www.drive.google.com/
如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板中进行了说明。如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。
正则表达式电路
jex.im可视化正则表达式:
推荐阅读
- ffmpeg - 使用 ffmpeg 将 Logitech C920 视频传输到两个输出:重新编码为 RTMP 流和硬件编码为文件
- python - 有什么方法可以优化使用 pandas 读取 TSV 文件、进行转换并使用 spark 写入表的代码?
- mysql - 获取跨多个表的不同值的计数(MySQL)
- php - 如果用户单击链接并来自不同页面,如何在 php 页面中显示消息
- batch-file - 使用 bat 文件在单独的窗口中打开 dotnet 应用程序
- reactjs - 如何通过redux react js调用一个函数到另一个函数
- android - 在带有滚动视图的 Android 响应式设计屏幕中并使其具有响应性?
- fullcalendar - FullCalendar:弃用警告:提供的值不是可识别的 RFC2822 或 ISO 格式
- json - 为什么 JSON 字符串会使用 bash shell 进行转换
- css - flex布局中的Angular Material进度微调器大小