Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect and replace non-printable characters in a string using Java?

For instance I have a string like this : abc123[*]xyz[#]098[~]f9e

[*] , [#] and [~] represents 3 different non-printable characters. How can I replace them with "X" in Java ?

Frank

like image 415
Frank Avatar asked Oct 14 '22 08:10

Frank


2 Answers

I'm not sure if I understand your questions. If you can formulate it better, I think a simple regular expression replacement may be all that you need.

String r = s.replaceAll(REGEX, "X");

REGEX depends on what you need:

"\\*|#|~"   : matches only '*', "#', and '~'
"[^\\d\\w]" : matches anything that is neither a digit nor a word character
"\\[.\\]"   : matches '[' followed by ANY character followed by ']'
"(?<=\\[).(?=\\])" : matches only the character surrounded by '[' and ']'
like image 69
polygenelubricants Avatar answered Oct 18 '22 12:10

polygenelubricants


This SO Q&A shows a way to test, in Java, whether a given character is printable.

As you surely know, in Java you cannot directly alter a string: rather, you make a new StringBuilder object initialized with the string, alter the string builder object (e.g. with setCharAt calls where the method above-mentioned shows the character at that index isn't printable), and finally call toString on the string builder object to make a new string object, which you can return from your method, or assign to the same identifier you were using to refer to the original string, etc, etc, depending on your exact needs.

like image 22
Alex Martelli Avatar answered Oct 18 '22 13:10

Alex Martelli