如何使用 Java 检测和替换字符串中的不可打印字符?
例如我有一个像这样的字符串: abc123[*]xyz[#]098[~]f9e
[*] 、 [#] 和 [~] 代表 3 个不同的不可打印字符。 如何在 Java 中将它们替换为“X”?
坦率
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定我是否理解你的问题。如果你能更好地表达它,我认为一个简单的正则表达式替换可能就是你所需要的。
正则表达式取决于您的需要:
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.
REGEX depends on what you need:
此问答展示了一种在 Java 中测试给定字符是否可打印的方法。
您肯定知道,在 Java 中您不能直接更改字符串:相反,您可以创建一个新的 StringBuilder 使用字符串初始化的对象,更改字符串生成器对象(例如,使用
setCharAt
调用,其中上述方法显示该索引处的字符不可打印),最后在字符串构建器对象上调用toString
来创建一个新的字符串对象,您可以从您的方法返回该对象,或者分配给您用于引用该对象的相同标识符原始字符串等,取决于您的具体需要。This SO Q&A shows a way to test, in Java, whether a given character is printable.
As you surely know, in Java you cannot directly alter a string: rather, you make a new StringBuilder object initialized with the string, alter the string builder object (e.g. with
setCharAt
calls where the method above-mentioned shows the character at that index isn't printable), and finally calltoString
on the string builder object to make a new string object, which you can return from your method, or assign to the same identifier you were using to refer to the original string, etc, etc, depending on your exact needs.