如何使用Java检测和替换字符串中不可打印的字符?
问题描述:
例如,我有一个像这样的字符串:abc123 [*] xyz [#] 098 [〜] f9e
For instance I have a string like this : abc123[*]xyz[#]098[~]f9e
[*],[#]和[〜]代表3个不同的不可打印字符. 如何在Java中将它们替换为"X"?
[*] , [#] and [~] represents 3 different non-printable characters. How can I replace them with "X" in Java ?
坦率
答
我不确定我是否理解您的问题.如果您可以更好地制定公式,那么我认为可能只需要简单的正则表达式替换即可.
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 ']'