2017-05-26 54 views
0

即時通訊設法建立一個正則表達式,我嘗試過濾網址,只有那些沒有在我的正則表達式中給出的匹配。Java正則表達式:如果匹配字符串,如果它不包含某些頂級域名列表

如果url中沒有test1.com或test2.com,它應該會導致匹配。

我希望不會導致匹配的頂級域名(test1.com和test2.com)始終使用https協議,可以包含子域名並在頂級域名「.com」之後具有路徑。

最新嘗試是下面的,但仍不起作用...

https?://([a-z0-9]+[.])((test1)|(test2))[.](com)/.* 

結果上regexplanet:

https://abc.test1.com/test.htm 

==> MATCH

www.google.com 

==>不匹配

https://123.test2.com/test.html 

==> MATCH

https://test2.com/test.html 

==>敵不過

何我是否需要寫的正則表達式這已經不是test1.com和test2.com域的字符串一切會給一場比賽?

+0

如果你寫的正則表達式匹配,然後在Java代碼:如果(匹配){丟棄它? – Juan

+0

不能這樣做,因爲我需要把這個正則表達式字符串賦給正在處理這個正則表達式的另一個組件。 – StephanM

+0

嘗試'^ https?://(?![^ /] *(?:test1 \ .com | test2 \ .com))\ S + $' –

回答

2

這種模式應該工作:

^((?!test1\\.com|test2\\.com).)*$ 

試用:

System.out.println(Pattern.matches("^((?!test1\\.com|test2\\.com).)*$", "https://abc.test1.com/test.htm")); 
System.out.println(Pattern.matches("^((?!test1\\.com|test2\\.com).)*$", "www.google.com")); 
System.out.println(Pattern.matches("^((?!test1\\.com|test2\\.com).)*$", "https://123.test2.com/test.html")); 
System.out.println(Pattern.matches("^((?!test1\\.com|test2\\.com).)*$", "https://test2.com/test.html")); 

結果:

false 
true 
false 
false 
+0

完美!多謝... – StephanM

相關問題