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

For example, I have a line like this: abc123 [*] xyz [#] 098 [~] f9e

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

Franc

+4
source share
2 answers

I'm not sure how much I understand your questions. If you can articulate it better, I think that simply replacing the regex may be all 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 ']' 
+2
source

This SO Q & A shows how to test in Java whether a given character can be printed.

As you know for sure, in Java you cannot directly modify a string: instead, you create a new StringBuilder object initialized with string, modify a string builder object (for example, with setCharAt calls, where the above method shows that the character in this index is not printed) and finally, call toString on the string builder object to create a new string object that you can return from your method or assign to the same identifier that you used to refer to the original string, etc. etc., depending on your specific needs.

+2
source

Source: https://habr.com/ru/post/1304677/


All Articles