gpt4 book ai didi

java - 使用正则表达式模式验证域和子域的正则表达式是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:59:32 25 4
gpt4 key购买 nike

我有一个域和子域列表,我正在检查此列表中的每一项是否都是有效的域名(或子域),例如: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}(?:\/.*)?$

Demo 1

(?i)^(?:https?:\/\/)?(?:www\.)?(?:[a-z0-9-]{1,20}\.){1,9}[a-z]{2,5}(?:\/.*)?$

Demo 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 的右上面板中已对此进行了解释.如果你愿意,也可以在this link观看。 ,它将如何与一些样本输入相匹配。


正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于java - 使用正则表达式模式验证域和子域的正则表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57977513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com