简体   繁体   中英

How to remove embedded braces in Java string?

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

Try using simplest regex \\{\\w*\\} as below:

    String s  = "My name is {name}. I am a {animal}. I like to {activity} "+
                "whenever it rains.";
    System.out.println(s.replaceAll("\\{\\w*\\}", ""));

The above regex stripes the word characters enclosed in {}. If you want to include certain special characters then include them along with the \\w mentioned inside the braces.

replaceAll("\\\\{.*?\\\\}", "") should do the job

String stripped = "My name is {name}. I am a {animal}. I like to {activity} whenever it rains.".replaceAll("\\{.*?\\}", "");
System.out.println(stripped);

prints My name is . I am a . I like to whenever it rains. My name is . I am a . I like to whenever it rains.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM