如何使用 Java 检测和替换字符串中的不可打印字符?

Fra*_*ank 5 java replace character non-printable

例如我有一个这样的字符串:abc123[*]xyz[#]098[~]f9e

[*] 、 [#] 和 [~] 代表 3 个不同的不可打印字符。如何在 Java 中用“X”替换它们?

坦率

pol*_*nts 2

我不确定我是否理解你的问题。如果你能更好地表达它,我认为一个简单的正则表达式替换可能就是你所需要的。

String r = s.replaceAll(REGEX, "X");
Run Code Online (Sandbox Code Playgroud)

正则表达式取决于您的需要:

"\\*|#|~"   : 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 ']'
Run Code Online (Sandbox Code Playgroud)