2016-12-15 44 views
0

我想写一个正则表达式来检查URL包含cici1ci2stag如何检查URL是否包含/预览或子域是CI?

如果URL包含/preview

https://regex101.com/r/aKHx9g/2/tests

例如,正则表达式应该匹配

http://ci.company.com 
http://stag.company.com 
http://www.company.com/preview 
https://www.company.com/preview 

这一个不应该匹配

http://www.company.com/article 
http://company.com/article 
https://company.com/article 

不知道正则表达式是能够明白了吗?

我似乎无法想出在正则表达式中做OR条件。这是迄今为止我所拥有的。

https?:\/\/(ci|stag|ci2|ci3)\..* 
+0

试试这个''https?:\/\ /((ci | stag | ci2 | ci3)|(。* \/preview))。*' – GurV

+0

[https:// regex101。 COM/R/aKHx9g/4 /测试) – anubhava

回答

2

要在REG-EX做到这一点,你可以使用:

url.toString().matches("https?://(?:stag|ci|ci1|ci2)\\..*|.*/preview") 

注:没有必要逃避/字符。

(?: ...)创建一个非捕获组。

但是假设你有一个URL,那么你可能想使用:

URL url = ...; 
if (url.getHost().matches("(?:stag|ci|ci1|ci2)\\..*") || 
    url.getPath().endsWith("/preview")) { 
} 

这将防止对URL的错误的部分匹配。

3

您可以简单地使用String.contains(/*something*/)

if(url.contains("/preview") || url.contains("ci") /*and the other 
    things that you want to check*/){ 
    //do things accordingly 
} 
相关问题