Jister13
Jister13

Reputation: 203

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?

Upvotes: 5

Views: 20521

Answers (5)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

When you need to match a substring from a single character up to another single character, the best regex solution is to use the delimiters and insert in-between them a negated character class that matches any character but the delimiter characters.

So, the basic pseudo pattern is

a  [^ ab  ]*  b

where:

  • a - a starting delimiter
  • [^ab]* - zero or more characters other than a and b
  • b - a trailing delimiter.

So, to replace all text between { and } (between braces), use

String data = "text 1 {\ntext 2\ntext 3\n}";
System.out.println(data.replaceAll("\\{[^{}]*}", ""));
// => text 1

See the IDEONE demo

Note that in Java regex, { and } do not have to be escaped inside the character class, and } does not have to be escaped even outside of it. Only { outside of a character class must be escaped (or put into a character class) so as not to form a limiting quantifier construct.

Upvotes: 0

roblovelock
roblovelock

Reputation: 1981

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) {}"

Upvotes: 15

Rohit Srivastava
Rohit Srivastava

Reputation: 91

try this, may this will help you.

String refinedData = new String(data);
Pattern p = Pattern.compile("\\{[^\\}]*\\}");
Matcher m = p.matcher(data);
while(m.find()){
    String d = data.substring(m.start(), m.end());
    refinedData = refinedData.replace(d, "");
}

Upvotes: 1

Cruncher
Cruncher

Reputation: 7796

In general, this is a job that's not suited for regex to begin with. Usually if "{ text }" is possible then so is: "{ { text1 } { text2 } }" which cannot be parsed properly with regex.

This is the same reason why XML/HTML parsers do not use regex

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213391

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("\\{.*?}", "");

Upvotes: 5

Related Questions