Yuan Chen
Yuan Chen

Reputation: 1197

How to apply the escape characters in java string

My problem is I read a text from a file In the text file there is some text like that

Base64.valueOf("\030)?8*\"q1;16=\0331:?5/8~:8(6y", 42 - -33))

I able to get the text using regular expression

\030)?8*\"q1;16=\0331:?5/8~:8(6y

but the String is equal below statement

regText = "\\030)?8*\\"q1;16=\\0331:?5/8~:8(6y"

But the exact string I want is

expectedText = "\030)?8*\"q1;16=\0331:?5/8~:8(6y"

So how can I turn the regText to expectedText

In here it do almost what I expected

Except it is not turn the "\030" to "\030" instead it turn to "030"

Upvotes: 1

Views: 9652

Answers (2)

Deepak Bala
Deepak Bala

Reputation: 11185

Your problem becomes easier if the program writing to the file writes the data properly to begin with. If that is not possible use the StringEscapeUtils from apache commons lang.

System.out.println(StringEscapeUtils.unescapeJava("New line: \\n Tab: \\t"));

That call manually processes \n and converts it to a newline. It only handles literals. You are on your own for octals and other escapes. You can always fork the code and work on the octals too.

Upvotes: 1

zoom
zoom

Reputation: 1756

By using String#replaceAll you can do the following :

expectedText = regText.replaceAll("\\\\", "\\");

Which will replace the double backslashes in the regText string, to the simple backslashes that you expect.

Upvotes: 0

Related Questions