Java - Regex problem

2019-02-20 11:37发布

I have a list of URLs of type

  • http://www.example.com/pk/ca,
  • http://www.example.com/pk,
  • http://www.example.com/anthingcangoeshere/pk, and
  • 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

标签: java regex url
4条回答
我想做一个坏孩纸
2楼-- · 2019-02-20 11:56
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. If you don't add $ to the end of the pattern, then http://www.exampke.com/pk/foobar will be accepted too.

查看更多
倾城 Initia
3楼-- · 2019-02-20 11:58

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:

If you use find():

\.com/pk/?$

If you use matches():

.*\.com/pk/?

Other answers given here give more restrictive patterns, allowing only URLs that are more close to your examples. Especially my pattern does not validate that the given string is a syntactically valid URL.

查看更多
淡お忘
4楼-- · 2019-02-20 12:14

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
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-20 12:16
String pattern = "^https?://(www\.)?.+\\.com/pk/?$";
查看更多
登录 后发表回答