Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java function which parses escaped characters?

Tags:

java

string

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?

like image 433
Daniel Rikowski Avatar asked Aug 25 '09 10:08

Daniel Rikowski


People also ask

How do you escape the escape character in Java?

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must be enclosed in quotation marks ("").

What is the function of escape character?

Escape sequences allow you to send nongraphic control characters to a display device. For example, the ESC character (\033) is often used as the first character of a control command for a terminal or printer. Some escape sequences are device-specific.

Does Java have escape sequences?

Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence. The Java compiler takes an escape sequence as one single character that has a special meaning.

What is the function that can be used to remove escape characters in a string?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “). Example: This example illustrates the use of the str_replace() function to remove the special characters from the string.


2 Answers

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-

like image 82
Emmanuel Bourg Avatar answered Nov 03 '22 01:11

Emmanuel Bourg


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");
like image 20
Sean Owen Avatar answered Nov 03 '22 00:11

Sean Owen