简体   繁体   English

查找并替换括号中的字符

[英]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/ https://regex101.com/

In order to use it in Java, remember to add second backslashes: 为了在Java中使用它,请记住添加第二个反斜杠:

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

It matches 0 or more letters (uppercase or lowercase) preceded by either of these [,{,( and followed by either of these ],},). 它匹配0个或多个字母(大写或小写),后跟这些[,{,(后面的任何一个,,},)中的一个。

If you want to have at least 1 letter between brackets just replace '*' with '+' like this: 如果要在方括号之间至少包含1个字母,只需将“ *”替换为“ +”,如下所示:

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

GCP showed how to use look aheads and look behinds to exclude the brackets from the matched part. GCP展示了如何使用前瞻性和后瞻性从匹配的部分中排除括号。 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 [] . 字符组[] OR。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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