-3

How do I replace text between braces {...} including newline with regex in java?

I've seen many related questions about removing text within brackets but the main problem here is that if there's a new line in the middle of the match, it sort of seems to not match.

Any help on how to do that properly is appreciated, thanks!

Example:

Input:

text 1 {
text 2
text 3
}

Output after replacement:

text1
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
bmo
  • 147
  • 1
  • 11
  • use `System.out.println("text 1 {\ntext 2\ntext 3\n}".replaceAll("(?s)\\{.*\\}", ""));` – rock321987 May 23 '16 at 19:55
  • 1
    see http://stackoverflow.com/questions/6500036/pattern-dotall-with-string-replaceall you can use `PATTERN.DOTALL` or prepend `(?s)` – user140547 May 23 '16 at 19:56
  • By virtue of the fact you state Open-Clos brace, it reeks of balance text. Otherwise, why not just match `}{`. There is no real construct in language that doesn't parse _nesting_ syntax. Java doesn't support it. Move on, nothing to see... –  May 23 '16 at 20:31

2 Answers2

1

Learned that . is not literally every character.

I'm using

string = string.replaceAll("\\{(.|\\n|\\r|\\t)*?\\}","");

and now it's working.

bmo
  • 147
  • 1
  • 11
0

You could simply do this:

string=string.replaceAll("\\{(.|\n)*?\\}","");

I hope it helps.

joel314
  • 1,060
  • 1
  • 8
  • 22