Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all text between braces { } in Java with regex

Tags:

java

string

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?

like image 519
Jister13 Avatar asked Nov 29 '22 12:11

Jister13


2 Answers

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 = Pattern.compile("(?<=\\{).*?(?=\\})", Pattern.DOTALL).matcher(data).replaceAll("");

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

like image 166
roblovelock Avatar answered Dec 05 '22 18:12

roblovelock


You need to escape the opening brace as it denotes the start of the quantifier - {n} in regex. And you don't really need that capture groups, so remove it.

data = data.replaceAll("\\{.*?}", "");
like image 23
Rohit Jain Avatar answered Dec 05 '22 18:12

Rohit Jain