我需要匹配或替换字符串的一部分,如下所示,但我无法在 java 中编写准确的正则表达式。
字符串:
text1${text2${text3}text4}text5
预期的正则表达式应该单独匹配 test3,即。 “内部”${} 内的任何内容。上面的示例有一个外部 ${...} 和一个内部 ${...},例如 ...${...${...}...}.... 并且 test3 位于“内部 ${} 这就是我想要的。
以下正则表达式捕获 ${...} 内的全部内容,而不仅仅是“内部”${...} 的内容
\$\{(.*?)\}
更多示例:
text1${text2${text3}text4}text5 - match "text3"
text1text2${text3}text4text5 - should not match anything
text1${text2${text3}text4text5 - should not match anything
更新:
text1${text2${text3}${text4}text5} - match "text3" and "text4"
最佳答案
.
匹配 {
和 }
。您需要排除匹配的 {
和 }
:
\$\{([^{}]*)}
^^^^^
请参阅regex demo 。 [^{}]*
是 negated character class匹配 0+ 个除 {
和 }
之外的字符。
String str = "text1${text2${text3}text4}text5";
Pattern p = Pattern.compile("\\$\\{([^{}]*)}");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
// => text3
关于java - 用于获取匹配项或替换子字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034960/