9

I'm looking for a built-in Java functions which for example can convert "\\n" into "\n".

Something like this:

assert parseFunc("\\n") = "\n"

Or do I have to manually search-and-replace all the escaped characters?

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329

4 Answers4

12

You can use StringEscapeUtils.unescapeJava(s) from Apache Commons Lang. It works for all escape sequences, including Unicode characters (i.e. \u1234).

https://commons.apache.org/lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html#unescapeJava-java.lang.String-

Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
5

Anthony is 99% right -- since backslash is also a reserved character in regular expressions, it needs to be escaped a second time:

result = myString.replaceAll("\\\\n", "\n");
Sean Owen
  • 66,182
  • 23
  • 141
  • 173
1

Just use the strings own replaceAll method.

result = myString.replaceAll("\\n", "\n");

However if you want match all escape sequences then you could use a Matcher. See http://www.regular-expressions.info/java.html for a very basic example of using Matcher.

Pattern p = Pattern.compile("\\(.)");
Matcher m = p.matcher("This is tab \\t and \\n this is on a new line");
StringBuffer sb = new StringBuffer();
while (m.find()) {
   String s = m.group(1);
   if (s == "n") {s = "\n"; }
   else if (s == "t") {s = "\t"; } 
   m.appendReplacement(sb, s);
}
m.appendTail(sb);
System.out.println(sb.toString());

You just need to make the assignment to s more sophisticated depending on the number and type of escapes you want to handle. (Warning this is air code, I'm not Java developer)

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • Won't that be a performance drain if I do a replaceAll for every escapable character, i.e. 8 times? (http://java.sun.com/docs/books/tutorial/java/data/characters.html) – Daniel Rikowski Aug 25 '09 at 11:26
  • Sorry I was just showing an anwser to your simple case (its a knee-jerk that many of us do it doesn't really answer your question). Thats why I point you at the Matcher class, which in combination with a StringBuffer you can create a result string in one pass. – AnthonyWJones Aug 25 '09 at 11:34
0

If you don't want to list all possible escaped characters you can delegate this to Properties behaviour

    String escapedText="This is tab \\t and \\rthis is on a new line";
    Properties prop = new Properties();     
    prop.load(new StringReader("x=" + escapedText + "\n"));
    String decoded = prop.getProperty("x");
    System.out.println(decoded);

This handle all possible characters

Emanuele
  • 469
  • 2
  • 10