qumm
qumm

Reputation: 157

invalid escape sequence ERROR

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

n

but it gives me an error in Java

enter image description here

What is wrong with that regex?

Upvotes: 1

Views: 1621

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726549

The problem with escape sequences in Java regexes entered as literals is that they are interpreted twice:

  • First, Java compiler interprets each escape sequence as part of parsing string literals,
  • Second, Java Regex engine interprets the remaining escape sequences as part of preparing the pattern for matching

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

rodridevops
rodridevops

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

Related Questions