英文:
Java regex: custom URL
问题
你好,以下是翻译好的内容:
如何创建一个正则表达式,用于匹配满足以下条件的URL:
- 包含:q=help
- 且
- 不包含:sort=
一些符合正则表达式的示例URL:
- http://www.example.com/homepage?q=help
- http://www.example.com/homepage?page=1&q=help&pagesize=25
一些不符合正则表达式的示例URL:
- http://www.example.com/homepage?sort=date
- http://www.example.com/homepage?q=help&sort=date
- http://www.example.com/homepage?sort=date&q=help
- http://www.example.com/homepage?page=1
提前感谢!
英文:
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:
- http://www.example.com/homepage?q=help
- http://www.example.com/homepage?page=1&q=help&pagesize=25
Some example URLs, which would not match the regex:
- http://www.example.com/homepage?sort=date
- http://www.example.com/homepage?q=help&sort=date
- http://www.example.com/homepage?sort=date&q=help
- http://www.example.com/homepage?page=1
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论