我需要一个正则表达式来验证这样的 URL:
- 有效
- http://url-example.com
- http://url-example.com/anything
- http://www.url-example.com
- http://www.url-example.com/anything
- 无效
- http://url-example.com .br(无效)
- http://www.url-example.com .br(无效)
- http://www.url-example.com .br/anything(无效)
主要目标是忽略所有以 .br 或 结尾的 .br 加上子目录的 URL。
在 Java 中我正在这样做:
Pattern.compile("http:\\/\\/(www\\.)?url-example.com^(\\.br).*");
但它不起作用...我相信 ^(\\.br)
出了问题。有什么方法可以使用正则表达式实现这种验证吗?
最佳答案
使用如下所示的否定前瞻。
Pattern.compile("http://(www\\.)?url-example\\.com(?!.*\\.br\\b).*");
(?!.*\\.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/