我有一种字符串:
String text = "(plum) some other words, [apple], another words {pear}.";
我必须找到并替换括号中的单词,不要替换括号本身。
如果我写:
text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");
我得到:
fruit some other words, fruit, another words fruit.
所以括号和水果一起消失了,但我需要保留它们。
<小时/>期望的输出:
(fruit) some other words, [fruit], another words {fruit}.
最佳答案
这是您的正则表达式:
(?<=[({\[\(])[A-Za-z]*(?=[}\]\)])
在这里测试一下:
为了在 Java 中使用它,请记住添加第二个反斜杠:
(?<=[({\\[\\(])[A-Za-z]*(?=[}\\]\\)])
它匹配 0 个或多个字母(大写或小写),前面带有这些 [,{,( 后面带有 ],},)。
如果您希望括号之间至少有 1 个字母,只需将“*”替换为“+”,如下所示:
(?<=[({\[\(])[A-Za-z]+(?=[}\]\)])
关于java - 查找并替换括号中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47675203/