简体   繁体   中英

Find and replace characters in brackets

I have a string kind of:

String text = "(plum) some other words, [apple], another words {pear}.";

I have to find and replace the words in brackets, don't replacing the brackets themselves.

If I write:

text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");

I get:

fruit some other words, fruit, another words fruit.

So the brackets went away with the fruits, but I need to keep them.


Desired output:

(fruit) some other words, [fruit], another words {fruit}.

Here is your regex:

(?<=[({\[\(])[A-Za-z]*(?=[}\]\)])

Test it here:

https://regex101.com/

In order to use it in Java, remember to add second backslashes:

(?<=[({\\[\\(])[A-Za-z]*(?=[}\\]\\)])

It matches 0 or more letters (uppercase or lowercase) preceded by either of these [,{,( and followed by either of these ],},).

If you want to have at least 1 letter between brackets just replace '*' with '+' like this:

(?<=[({\[\(])[A-Za-z]+(?=[}\]\)])

GCP showed how to use look aheads and look behinds to exclude the brackets from the matched part. But you can also match them, and refer to them in your replacement string with capturing groups:

text.replaceAll("([\\(\\[\\{]).*?([\\)\\]\\}])", "$1fruit$2");

Also note that you can replace the | ORs by a character group [] .

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