47

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!

Ashvin Sharma
  • 563
  • 1
  • 5
  • 24
MJB
  • 3,934
  • 10
  • 48
  • 72
  • 2
    I'm surprised that you can even compile \s in a string literal. Adding \t in a string literal would create a regular expression containing a tab character, rather than the regular expression with \t in it, for that you need \\t in the string literal. – Geoff Apr 28 '10 at 21:35
  • I couldn't compile it,.. eclipse gave me this error message I posted. I just wanted to let you know what I was trying to do. – MJB Apr 28 '10 at 22:20

3 Answers3

73

You need to escape the slash

start_from  = start_from.replaceAll("\\s", "+");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
  • 5
    thank you! awesome website! :-) "You cannot accept an answer in 11 minutes" .... ;-) – MJB Apr 28 '10 at 21:30
12

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", "+");
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
1

You can use the java.util.regex.Pattern class and use something like p = Pattern.compile("\s"); in combination with p.matcher(start_from).replaceAll("+"). Alternatively, just escape your "\s" metacharacter as "\\s".

Dustin
  • 1,956
  • 14
  • 14
  • jepp I already used a pattern in another part of my code, however, I thought it would be easier in this case to just use replaceAll(..) thank you! – MJB Apr 28 '10 at 21:37