如何使用Java检测和替换字符串中不可打印的字符? [英] How to detect and replace non-printable characters in a string using Java?

查看:287
本文介绍了如何使用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 ']'

这篇关于如何使用Java检测和替换字符串中不可打印的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆