java - 替换java中的多行字符串
问题描述
尝试使用 replaceAll 方法替换 java 中的多行字符串,但它不起作用。下面的逻辑有什么问题吗?
String content=" \"get\" : {\n" +
" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",\n" +
" \"details\" : \"Test details\"";
String searchString=" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
尝试了以下选项,但都没有奏效-
Pattern.compile(searchString, Pattern.MULTILINE).matcher(content).replaceAll(replaceString);
Pattern.compile(searchString, Pattern.DOTALL).matcher(content).replaceAll(replaceString);
content = content.replaceAll(searchString, replaceString);
解决方案
免责声明:您不应使用正则表达式来操作具有无限嵌套内容的 JSON 或 XML。有限自动化不适用于操作这些数据结构,您应该改用 JSON/XML 解析器。
话虽这么说,纯粹出于学习目的,我会快速修复您的代码。
1)使用其中replace
之一而不是replaceAll
避免您searchString
被解释为正则表达式:
String content=" \"get\" : {\n" +
" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",\n" +
" \"details\" : \"Test details\"";
String searchString=" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
System.out.println(content.replace(searchString, replaceString));
输出:
"get" : {
"name" : [ "Actual" ],
"description" : "Replaced description",
"details" : "Test details"
2)或使用replaceAll
但转义括号以避免它们被解释为字符类定义尝试。
String searchString=" \"name\" : \\[ \"Test\" \\],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
System.out.println(content.replaceAll(searchString, replaceString));
输出:
"get" : {
"name" : [ "Actual" ],
"description" : "Replaced description",
"details" : "Test details"
- 你应该在一个对象中加载你的 json 结构
- 将该对象的属性值更改为新值
- 以json格式再次导出
推荐阅读
- javascript - 传递给函数的值变得未定义
- r - 将字符串添加为具有定义函数的公式
- ios - 首次启动应用程序 Xcode 11 iOS 13 后如何使入职场景消失
- java - 包文件夹在哪里?那应该存储在android设备中吗?
- javascript - select2,无法选择 AJAX 结果
- java - 从firebase获取坐标以绘制折线
- javascript - 将 JavaScript 变量发送到 PHP
- java - 用户输入不是调用方法(Java)
- python - 如何使用 distinct() 为 Django ListView 中的每个标题项仅显示来自子模型的一条记录
- permissions - docker-compose 命令执行问题 - 在 /var/www/ 中设置权限