3

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?

1
  • 1
    \ in a string needs to be escaped. Use \\ . It becomes Pattern.compile("([A-Z][a-zA-Z]+)\\s+\\1"); Commented Nov 16, 2011 at 15:59

1 Answer 1

7

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.

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

4 Comments

Java oh Java, when are you going to have verbatim strings?
@NullUserExceptionఠ_ఠ... if only - maybe in Java 10, 11, or 12? or do I remember reading somewhere that that's considered "syntactical candy" or something similar?
@CodeJockey Did you mean "syntactic sugar"?
@NullUserExceptionఠ_ఠ - YEAH! I knew it didn't sound quite right, but kinda close-ish (and I was too lazy to take the time to type it into Google)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.