用正则表达式替换Java中的大括号{}之间的所有文本 [英] Replace all text between braces { } in Java with regex
问题描述
我有一个很长的字符串,{}之间有很多文字出现我想删除但是当我这样做时:
I have a long string with numerous occurences of text between { } that I would like to remove however when I do this:
data = data.replaceAll("{(.*?)}", "");
我收到错误,所以我做错了什么/我应该怎么做?
i get an error, so what am I doing wrong / how should I go about doing this?
推荐答案
这将替换大括号之间的所有文本并保留括号
这是使用正向前看和正面看完后面
This will replace all text between curly brackets and leave the brackets This is done using positive look ahead and positive look behind
data = data.replaceAll("(?<=\\{).*?(?=\\})", "");
if(true){calc();}变为if(true){}
"if (true) { calc(); }" becomes "if (true) {}"
这将替换大括号之间的所有文本并删除括号
This will replace all text between curly brackets and remove the brackets
data = data.replaceAll("\\{.*?\\}", "");
if(true){calc();}变为if(true)
"if (true) { calc(); }" becomes "if (true)"
这将替换大括号之间的所有文本,包括新行。
This will replace all text between curly brackets, including new lines.
data = Pattern.compile("(?<=\\{).*?(?=\\})", Pattern.DOTALL).matcher(data).replaceAll("");
if(true){\ n\t\tcalc(); \ n }变成if(true){}
"if (true) { \n\t\tcalc();\n }" becomes "if (true) {}"
这篇关于用正则表达式替换Java中的大括号{}之间的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!