简体   繁体   English

Java-正则表达式问题

[英]Java - Regex problem

I have a list of URLs of type 我有一个URL类型列表

  • http://www.example.com/pk/ca , http://www.example.com/pk/ca
  • http://www.example.com/pk , http://www.example.com/pk
  • http://www.example.com/anthingcangoeshere/pk , and http://www.example.com/anthingcangoeshere/pk ,以及
  • http://www.example.com/pkisnotnecessaryhere . http://www.example.com/pkisnotnecessaryhere

Now, I want to find out only those URLs that ends with /pk or /pk/ and don't have anything in between .com and /pk 现在,我只想查找那些以/pk/pk/结尾的URL,而.com/pk之间没有任何内容

Your problem isn't fully defined so I can't give you an exact answer but this should be a start you can use: 您的问题尚未完全定义,所以我无法给您确切的答案,但这应该是您可以使用的开始:

^[^:]+://[^/]+\.com/pk/?$

These strings will match: 这些字符串将匹配:

http://www.example.com/pk
http://www.example.com/pk/
https://www.example.com/pk

These strings won't match: 这些字符串不匹配:

http://www.example.co.uk/pk
http://www.example.com/pk/ca
http://www.example.com/anthingcangoeshere/pk
http://www.example.com/pkisnotnecessaryhere
String pattern = "^http://www.example.com/pk/?$";

Hope this helps. 希望这可以帮助。

Some details: if you don't add ^ to the beginning of the pattern, then foobarhttp://www.example.com/pk/ will be accepted too. 一些细节:如果您不将^添加到模式的开头,那么foobarhttp://www.example.com/pk/也将被接受。 If you don't add $ to the end of the pattern, then http://www.exampke.com/pk/foobar will be accepted too. 如果您不将$添加到模式末尾,则也将接受http://www.exampke.com/pk/foobar

Directly translating your request "[...] URLs that ends with /pk or /pk/ and don't have anything in between .com and /pk", with the additional assumption that there shall always be a ".com", yields this regex: 直接翻译您的请求“ [...]以/ pk或/ pk /结尾并且在.com和/ pk之间没有任何内容的URL”,并假设始终有一个“ .com”,产生此正则表达式:

If you use find() : 如果使用find()

\.com/pk/?$

If you use matches() : 如果使用matches()

.*\.com/pk/?

Other answers given here give more restrictive patterns, allowing only URLs that are more close to your examples. 此处给出的其他答案提供了更多限制性模式,仅允许使用更接近示例的URL。 Especially my pattern does not validate that the given string is a syntactically valid URL. 特别是我的模式无法验证给定的字符串是否是语法有效的URL。

String pattern = "^https?://(www\.)?.+\\.com/pk/?$";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM