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

发布于 2024-08-26 03:47:10 字数 120 浏览 3 评论 0原文

例如我有一个像这样的字符串: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神仙妹妹 2024-09-02 03:47:10

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

String r = s.replaceAll(REGEX, "X");

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

"\\*|#|~"   : 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 ']'

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 ']'
水波映月 2024-09-02 03:47:10

此问答展示了一种在 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 call toString 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文