1

I have problems using a url-checker regex to match twitters picture urls.
The url looks like this:

String twitterPictureURL = "pic.twitter.com/123abc";

My regex looks like this:

String regex = "^(?:http(s)?:\\/\\/)?\\[\\w.-\\]+(?:\\.\\[\\w\\.-\\]+)+\\[\\w\\-\\._~:/?#\\[\\\\]@!\\$&'\\(\\)\\*\\+,;=.\\]+$";

The regex works if i try it online but when i use it in my code it does not work anymore.
I use it like this:

Pattern pattern = Pattern.compile(regex);  
if(pattern.matcher(twitterPictureUrl).matches())
{
  //match
}
else
{
  //no match
}
Didi
  • 29
  • 5
  • 3
    You failed to escape backslash matching patterns and hyphens. It also seems you escaped character class boundaries and thus corrupted these pattern parts. Share your regex demo link. – Wiktor Stribiżew Jan 15 '19 at 08:04
  • I used this demo [link](https://www.regextester.com/94502). I escaped the character class because when i did not i would get a "Unclosed Character class" exception. In this post [link](https://stackoverflow.com/questions/8126339/unclosed-character-class-near-index-nnn) it was mentioned that i need to escape the brackets to fix the problem – Didi Jan 15 '19 at 08:08
  • Does this work for you: `(?:https?://)?(?:\w*?\.)?pic\.twitter\.com/(\w+)` – Lino Jan 15 '19 at 08:09
  • 2
    You need to use `"^(?:https?://)?[\\w.-]+(?:\\.[\\w.-]+)+[\\w.~:/?#\\[\\]@!$&'()*+,;=.-]+$"`. It seems the root cause was an incorrectly escaped square bracket – Wiktor Stribiżew Jan 15 '19 at 08:10
  • @WiktorStribiżew thanks this works for me. But I don't get it can you explain why? – Didi Jan 15 '19 at 08:11
  • @Lino Workrs for this kind of link. Thank you. – Didi Jan 15 '19 at 08:13
  • You must escape `]` and `[` when used inside a character class. In JS regex, you only must escape `]` there. – Wiktor Stribiżew Jan 15 '19 at 08:13
  • @WiktorStribiżew ah ok. Thank you very much – Didi Jan 15 '19 at 08:14

0 Answers0