Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java doesn't work with regex \s, says: invalid escape sequence

I want to replace all whitespace characters in a string with a "+" and all "ß" with "ss"... it works well for "ß", but somehow eclipse won't let me use \s for a whitespace.. I tried "\t" instead, but it doesn't work either.. I get the following error:

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )

this is my code:

try {     String temp1 = from.getText().toString();     start_from  = temp1.replaceAll("ß", "ss");     start_from  = start_from.replaceAll("\s", "+"); } 

why doesn't it work? is it a problem with android, eclipse or what?

thanks in advance!

like image 631
MJB Avatar asked Apr 28 '10 21:04

MJB


People also ask

What is \s in Java regex?

The regular expression \s is a predefined character class. It indicates a single whitespace character. Let's review the set of whitespace characters: [ \t\n\x0B\f\r] The plus sign + is a greedy quantifier, which means one or more times.

How do you escape special characters in regex Java?

To escape a metacharacter you use the Java regular expression escape character - the backslash character. Escaping a character means preceding it with the backslash character. For instance, like this: \.

What is invalid escape sequence?

A string contains a literal character that is a reserved character in the Regex class (for example, the '(' or open parentheses character). Placing a '\' (backslash) in front of the character in the regular expression generates an 'Invalid escape sequence' compilation error.

What is the use of \\ s+ in Java?

\\s - matches single whitespace character. \\s+ - matches sequence of one or more whitespace characters.


2 Answers

You need to escape the slash

start_from  = start_from.replaceAll("\\s", "+"); 
like image 123
Rob Di Marco Avatar answered Sep 22 '22 09:09

Rob Di Marco


The problem is that \ is an escape character in java as well as regex patterns. If you want to match the regex pattern \n, say, and you'd go ahead and write

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

The regex pattern would not end up being \n: it would en up being an actual newline, since that's what "\n" means in Java. If you want the pattern to contain a backslash, you'll need to make sure you escape that backslash, so that it is not treated as a special character within the string.

replaceAll("\\s", "+"); 
like image 25
David Hedlund Avatar answered Sep 23 '22 09:09

David Hedlund