【问题标题】:How to check if a URL contains /preview or the subdomain is CI?如何检查 URL 是否包含 /preview 或子域是 CI?
【发布时间】:2016-12-16 04:06:01
【问题描述】:

我正在尝试编写正则表达式来检查 URL 是否包含 cici1ci2stag

如果网址包含/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)\..*

【问题讨论】:

标签: java regex


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    要在正则表达式中执行此操作,您可以使用:

    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 的错误部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2018-02-05
      • 2014-10-23
      相关资源
      最近更新 更多