替换java中的多行字符串
尝试使用replaceAll方法替换java中的多行字符串,但它不起作用。下面的逻辑有什么问题吗替换java中的多行字符串,java,regex,java-8,Java,Regex,Java 8,尝试使用replaceAll方法替换java中的多行字符串,但它不起作用。下面的逻辑有什么问题吗 String content=" \"get\" : {\n" + " \"name\" : [ \"Test\" ],\n" + " \"description\" : \"Test description to replace\",\n" + " \"details\" : \"Test details\"
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"
"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"
"get" : {
"name" : [ "Actual" ],
"description" : "Replaced description",
"details" : "Test details"
链接:
- 您应该在对象中加载json结构
- 将该对象属性的值更改为新值
- 以json格式再次导出它
[
括号(将其更改为\\[
)。可能这已经解决了。您可以在开始时用\Q
引用整个搜索字符串,或者调用模式。quote()
使用如下内容:String str=content.replaceAll(\\n“,”);由于您不使用正则表达式,请使用简单的content=content.replace(searchString,replaceString);
或更复杂的content=Pattern.compile(searchString,Pattern.LITERAL).匹配器(content).replaceAll(replaceString)
。如果您想保留编译的结果并多次使用它,后者是有意义的。然后,您可以从准备中获得好处,例如后台使用的Boyer–Moore算法。