Reputation: 157
I'm working on REGEX to validate domain.
My regular expression are like below:
Pattern REGEX = Pattern.compile("^([a-z]*|\*)\.([a-z]*)\.([a-z]*)");
It works well here
but it gives me an error in Java
What is wrong with that regex?
Upvotes: 1
Views: 1621
Reputation: 726549
The problem with escape sequences in Java regexes entered as literals is that they are interpreted twice:
An important consequence of this is that you must escape each slash in the expression in order for it to make it through the Java compile stage to the regex compile stage:
Pattern REGEX = Pattern.compile("^([a-z]*|\\*)\\.([a-z]*)\\.([a-z]*)");
This may not be the most readable solution, so another alternative would be to use character classes in place of escaped single characters:
Pattern REGEX = Pattern.compile("^([a-z]*|[*])[.]([a-z]*)[.]([a-z]*)");
Upvotes: 1
Reputation: 1987
\
is an escape character in java. To avoid this you have to append an extra \
to your code, like this:
Pattern REGEX = Pattern.compile("^([a-z]*|\\*)\\.([a-z]*)\\.([a-z]*)");
Docs: Characters
Upvotes: 0