0

I have a column in database which contains non printable characters;

String xyz = "Company Name\r\n Magna";

Once retrieved from database, in java, the values is shown as below

String companyname = "Company Name\\r\\n Magna";"

It adds an addtional escape character. How can i remove the non printable characters now ?

companyname.replaceAll("\\p{Cntrl}", ""); // Doesn't work.

Even if i use StringBuffer, it won't work because of additional escape character.

Please advice.

TeaCupApp
  • 11,316
  • 18
  • 70
  • 150
Abs
  • 458
  • 1
  • 7
  • 17
  • you don't have non-printable characters in your database, what you have is encoded character escapes in your database. you'll have to replace the escape strings directly. – jtahlborn Aug 18 '12 at 00:04
  • question is not clear. Do you have escape characters in the DB, or actually do you have plain ASCII letter which include backlashes (and which you want to interpret as escape characters? – leonbloy Aug 18 '12 at 00:06
  • @leonbloy - i'm pretty sure it's the latter. – jtahlborn Aug 18 '12 at 00:07
  • Perhaps relevant: http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java – leonbloy Aug 18 '12 at 00:09
  • I just wonder why you would write your application to store text in the database in that form in the first place .... – Stephen C Aug 18 '12 at 00:46
  • well some job inserted the non printable characters in the database, I am trying to recreate that scenario to add a fix to the code, hope that explains. – Abs Aug 18 '12 at 00:58

2 Answers2

2

You seem to have created a problem for yourself by the way that you have encoded the data before you put it into the database.

In the first instance, a replaceAll that replaces character sequences '\' 'r' and '\' 'n' is required; e.g.

text = text.replaceAll("\\\\r|\\\\n", "");

Note that in order to match the literal backslash characters they have to be escaped twice. One time for the string literal, and a second time because backslash is a metacharacter in regexes.

But, IMO, a better fix for this is to not encode CR and NL characters that way in your database. Can't you just represent them in the database without escaping?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

How about good old replace :

String text = readfromDatabase();
text = text.replace("\n", "").replace("\r", "");

or

text = text.replaceAll("\\r|\\n", "");

or

text = text.replaceAll("\\r", "").replaceAll("\\n", "");
ant
  • 22,634
  • 36
  • 132
  • 182