首页 > 解决方案 > 用java中的空格替换json字符串中的特殊字符(不可打印字符)

问题描述

试图用空格替换 json-string 中的特殊字符(不可打印字符)。它没有被替换。但是相同的正则表达式正在替换普通的 java 字符串。

String regex = "[\\x00-\\x1F]+";

带字符串

String text  = "To test\tthe\tspecial char\tin text and \rtab\t\n \t Check the interest";
text = text.replaceAll(regex, " ");

输出:

To test the special char in text and  tab    Check the interest

使用 JsonString(不工作)

String text = "{\"notes\":\"To test\\tthe\\tissues\\tin text and \\rtab\\t\\n \\tCheck the interest\"}";
text = text.replaceAll(regex, " ");

输出:

{"note_to_regulator":"To test\tthe\tissues\tin text and \rtab\t\n \tCheck the interest"}

在 json 字符串中,此正则表达式不起作用。我猜这是由于 json 字符串中的“\”转义字符,但不确定。请让我知道此正则表达式中所需的更改也可以在 json 字符串中正常工作。

标签: javajsonregex

解决方案


text = text.replaceAll("\\\\[lnrt]", " ").replace("\\\\", "\\");

"...\..." 是一个带有反斜杠的字符串,您的字符串实际上不包含控制字符,而是它们的表示形式。

正则表达式中的反斜杠转义,如digit必须写为\d,然后反斜杠本身在正则表达式中转义为:带有两个反斜杠的字符串。"\\d""\\\\"

第一个正则表达式replaceAll将处理换页、换行、回车和制表符。第二个普通字符串替换将用一个替换两个反斜杠。用 写这个会很有趣replaceAll,实际上反斜杠的数量增加了一倍。


推荐阅读