Search code examples
javareplacecharacternon-printable

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


Solution

  • 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 ']'