java - 正则表达式以避免 URL 中的可选组

标签 java regex

我需要一个正则表达式来验证这样的 URL:

主要目标是忽略所有以 .br 结尾的 .br 加上子目录的 URL。

在 Java 中我正在这样做:

Pattern.compile("http:\\/\\/(www\\.)?url-example.com^(\\.br).*");

但它不起作用...我相信 ^(\\.br) 出了问题。有什么方法可以使用正则表达式实现这种验证吗?

最佳答案

使用如下所示的否定前瞻。

Pattern.compile("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*");

DEMO

(?!.*\\.br) 负向先行断言 .com 后面的字符可以是任何字符,但不是 .br

String s1 = "http://url-example.com";
String s2 = "http://url-example.com/anything";
String s3 = "http://www.url-example.com";
String s4 = "http://www.url-example.com/anything";
String s5 = "http://url-example.com.br";
String s6 = "http://www.url-example.com.br";
String s7 = "http://www.url-example.com.br/anything";
System.out.println(s1.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s2.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s3.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s4.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s5.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s6.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));
System.out.println(s7.matches("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*"));

输出:

true
true
true
true
false
false
false

关于java - 正则表达式以避免 URL 中的可选组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27442174/

相关文章:

python - 在字符串中查找最重复(不是最常见)序列的算法(又名串联重复)

JavaScript 正则表达式

java - 如何用 Java 编写正确的微基准测试?

java - 如何从 Java 获取 jar 文件的主类名称?

java - 从 Unicode 字符串中获取字数(任何语言)

java - HTTP 请求处理程序连接重置错误

java - JWT spring security身份验证过滤器丢失 header 信息

python - 制作正则表达式Python

regex - 匹配一组几乎等效元素中的单个元素的正则表达式是什么?

javascript - 将正则表达式修饰符选项传递给 RegExp 对象