I have a Java string that may contain "{
" and "}
" pairs, multiple times, inside a larger string:
"My name is {name}. I am a {animal}. I like to {activity} whenever it rains."
etc. I am trying to write code that would strip out all instances of these pairs:
"My name is . I am a . I like to whenever it rains."
These pairs can occur anywhere inside the string, and may not occur at all. Obviously a String#replaceAll(someRegex, "")
is in order here, but I can't seem to get the someRegex
right:
// My best attempt.
String stripped = toStrip.replaceAll("{*}", "");
Any ideas? Thanks in advance.
To match {
, you would need to escape it. As it has some special meaning in regex. So, you need \\{
, and \\}
. Or you can also enclose them in a character class.
And then to match anything between them, you can use .*
. A dot (.)
matches any character. And *
is a quantifier, which means match 0 or more
.
So, your regex would be: -
\\{.*?\\}
or: -
[{].*?[}]
Note that, I have used a reluctant quantifier there - .*?
. Note the ?
at the end. It is used to match till the first }
in this case. If you use .*
instead of .*?
, your regex will cover the complete string from the first {
till the last }
, and replace everything.
Also, a special regex meta-characters, has no special meaning when used inside a character class
- that []
thing. That is why, you don't need to escape them when you use it like that. Hence the 2nd Regex.
That seems pretty simple, doesn't it? Ok, now is the time to go through some tutorial to learn more about Regular Expression
. You can start with http://www.regular-expressions.info/tutorial.html