-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?

thadeuszlay
  • 2,787
  • 7
  • 32
  • 67

1 Answers1

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.