java - 用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 字符串中正常工作。
解决方案
text = text.replaceAll("\\\\[lnrt]", " ").replace("\\\\", "\\");
"...\..." 是一个带有反斜杠的字符串,您的字符串实际上不包含控制字符,而是它们的表示形式。
正则表达式中的反斜杠转义,如digit必须写为\d
,然后反斜杠本身在正则表达式中转义为:带有两个反斜杠的字符串。"\\d"
"\\\\"
第一个正则表达式replaceAll
将处理换页、换行、回车和制表符。第二个普通字符串替换将用一个替换两个反斜杠。用 写这个会很有趣replaceAll
,实际上反斜杠的数量增加了一倍。
推荐阅读
- go - 带舵的尺码表
- ckeditor - TYPO3 9.5.4 CKEditor RTE 删除样式属性
- php - Get_where() 带有用户定义的子句
- ios - 如何使clang仅在发布时编译文件?
- javascript - 防止为两个字段输入相同的值 angular 6
- c# - 使用 tesseract 对收据进行图像预处理以获得更好的结果
- node.js - 使用 html-pdf 在 NodeJS 中创建 PDF 时出错
- typescript - 当我在 TypeScript 中收到“对象可能为空”错误时,我应该怎么做?
- r - 如何从 R 中的特定列中删除“\”符号
- powershell - VS Code 中的 Cmder 集成与 PowerShell 未按预期工作