Java正则表达式:自定义URL

huangapple go评论62阅读模式
英文:

Java regex: custom URL

问题

你好,以下是翻译好的内容:

如何创建一个正则表达式,用于匹配满足以下条件的URL:

  • 包含:q=help
  • 不包含:sort=

一些符合正则表达式的示例URL:

一些不符合正则表达式的示例URL:

提前感谢!

英文:

How can I create a regex, which matches a URL which:

  • Contains: q=help

AND

  • Doesn't contains: sort=

Some example URLs, which would match the regex:

Some example URLs, which would not match the regex:

Thanks in advance!

答案1

得分: 1

对于纯字符串选项,您可以使用 String#matches

String url = "http://www.example.com/homepage?q=help";
if (url.matches("(?!.*\\?.*\\bsort=).*\\?.*\\bq=help.*")) {
    System.out.println("MATCH");
}

该模式表示:

  • (?!.*\\?.*\\bsort=):断言查询字符串中不包含 sort=
  • .*\\?.*\\bq=help.*:然后匹配查询字符串中包含 q=help 的URL。
英文:

For a pure string option, you could use String#matches:

String url = "http://www.example.com/homepage?q=help";
if (url.matches("(?!.*\\?.*\\bsort=).*\\?.*\\bq=help.*")) {
    System.out.println("MATCH");
}

The pattern says to:

(?!.*\\?.*\\bsort=)    assert that sort= does NOT occur in the query string
.*\\?.*\\bq=help.*     then match a URL with q=help in the query string

huangapple
  • 本文由 发表于 2020年8月10日 17:29:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63337553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定