-1

I have this regex in JS flavor

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

I tried it in JS and it worked for me (only want to match URL that does not start with the HTTP/HTTPS protocol): https://regex101.com/r/6y2Gnd/2

Now I want to use the same regex in my Java backend. At first I got the error

Unclosed character class

Upon reading into it, I realized I have to escape the \ slash. I basically added three \\\ to every \ slash. The result is:

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

Even though the compiler doesn't show any errors anymore, the result was empty, i.e. it couldn't match the cases like it did with in JS flavor.

I tested the Java regex here and in my code.

www.web.de # I want to match this
web.de # I want to match this
http://web.de # I do NOT want to match this
https://www.web.de # I do NOT want to match this

Anyone know what I'm missing?

4
  • Why are you turning a single '\' into '\\\\'? Have you tried just '\\'? Commented Feb 23, 2020 at 23:40
  • @Jason Yes, I've tried that too: ^[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#\[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$. Still no matches. I escaped because of Java. I've been told that java behaves like that. Commented Feb 23, 2020 at 23:43
  • You only have one slash in front of the [ Commented Feb 23, 2020 at 23:45
  • Like so? ^[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#\[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$? Commented Feb 23, 2020 at 23:51

1 Answer 1

0

Following regex works well in Java regex tester:

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

Please try it yourself. Backslash should be added in the front of the [ character.

Sign up to request clarification or add additional context in comments.

3 Comments

I added ^[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#\[\]@!\$&'\(\)\*\+,;=.]+$ into freeformatter.com/java-regex-tester.html#ad-output But no matches found
I just tested and it works. Multiline checkbox should be selected.
Yes, you are right! It's working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.