13

Just something I don't understand the full meaning behind. I understand that I need to escape any special meaning characters if I want to find them using regex. And I also read somewhere that you need to escape the backslash in Java if it's inside a String literal. My question though is if I "escape" the backslash, doesn't it lose its meaning? So then it wouldn't be able to escape the following plus symbol?

Throws an error (but shouldn't it work since that's how you escape those special characters?):

replaceAll("\+\s", "")); 

Works:

replaceAll("\\+\\s", "")); 

Hopefully that makes sense. I'm just trying to understand the functionality behind why I need those extra slashes when the regex tutorials I've read don't mention them. And things like "\+" should find the plus symbol.

3
  • 1
    Related: Java regular expressions escape characters Commented Aug 5, 2014 at 18:45
  • Note that you will get an error if you say "\+\s" in any context, e.g. String s = "\+\s";. There's nothing special about string literals used as replaceAll parameters. Commented Aug 5, 2014 at 18:58
  • 1
    Just to keep us all on our toes, the formatting software used by SO also uses backslashes to make special things unspecial. That's why I had to add backticks to make the backslash visible in the last line of your question ("\+"). Commented Aug 5, 2014 at 19:53

2 Answers 2

22

There are two "escapings" going on here. The first backslash is to escape the second backslash for the Java language, to create an actual backslash character. The backslash character is what escapes the + or the s for interpretation by the regular expression engine. That's why you need two backslashes -- one for Java, one for the regular expression engine. With only one backslash, Java reports \s and \+ as illegal escape characters -- not for regular expressions, but for an actual character in the Java language.

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

1 Comment

@DoubleElite, Just to illustrate what rgettman said, put this in your program, and see what it prints out: System.out.println("\\+\\s");
1

Funda behind extra slashes is that , first slash '\' is escape for the string and second slash '\' is escape for the regex.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.