700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java替换花括号 用正则表达式替换Java中的大括号{}之间的所有文本

java替换花括号 用正则表达式替换Java中的大括号{}之间的所有文本

时间:2023-06-10 03:12:31

相关推荐

java替换花括号 用正则表达式替换Java中的大括号{}之间的所有文本

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(); }" becomes "if (true) {}"

This will replace all text between curly brackets and remove the brackets

data = data.replaceAll("\\{.*?\\}", "");

"if (true) { calc(); }" becomes "if (true)"

This will replace all text between curly brackets, including new lines.

data = pile("(?<=\\{).*?(?=\\})", Pattern.DOTALL).matcher(data).replaceAll("");

"if (true) { \n\t\tcalc();\n }" becomes "if (true) {}"

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。