tags:

views:

132

answers:

3

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?

+2  A: 

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
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)
DR
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
+1  A: 

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