Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal escape character error in Java regex

Tags:

java

regex

I've read the manual, and at the end there was an exercise:

Use a backreference to write an expression that will match a person's name only if that person's first name and last name are the same.

I've written the next program http://pastebin.com/YkuUuP5M
But when I compile it, I'm getting an error:

PersonName.java:18: illegal escape character
p = Pattern.compile("([A-Z][a-zA-Z]+)\s+\1");
                                      ^

If I rewrite 18 line in this way:

pattern = Pattern.compile(console.readLine("%nEnter your regex: "));

and write the pattern in the console, then the program works fine. Why I can't use the pattern as in the 1st program case and is there some way to fix it?

like image 795
user881259 Avatar asked Apr 02 '26 16:04

user881259


1 Answers

You want to get this text into a string:

([A-Z][a-zA-Z]+)\s+\1

However, \ in a string literal in Java source code is the character used for escaping (e.g. "\t" for tab). Therefore you need to use "\" in a string literal to end up with a single backslash in the resulting string. So you want:

"([A-Z][a-zA-Z]+)\\s+\\1"

Note that there's nothing regular-expression-specific to this. Any time you want to express a string containing a backslash in a Java string literal, you'll need to escape that backslash. Regular expressions and Windows filenames are just the most common cases for that.

like image 152
Jon Skeet Avatar answered Apr 04 '26 05:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!