我需要不受字符限制的字符串的 java 模式。
我有一个字符串(如下所述),其中一些大括号由单引号括起来,而其他大括号则不是。我想用另一个字符串替换不受单引号包围的大括号。
原始字符串:
this is single-quoted curly '{'something'}' and this is {not} end
需要转换成
this is single-quoted curly '{'something'}' and this is <<not>> end
请注意,未被单引号包围的大括号 { } 已替换为 << >>。
但是,我的代码打印(字符被吃掉)文本为
this is single-quoted curly '{'something'}' and this is<<no>> end
当我使用模式时
[^']([{}])
我的代码是
String regex = "[^']([{}])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
if ( "{".equals(matcher.group(1)) ) {
matcher.appendReplacement(strBuffer, "<<");
} else if ( "}".equals(matcher.group(1))) {
matcher.appendReplacement(strBuffer, ">>");
}
}
matcher.appendTail(strBuffer);
最佳答案
这是零宽度断言的一个明确用例。您需要的正则表达式不是很复杂:
String
input = "this is single-quoted curly '{'something'}' and this is {not} end",
output = "this is single-quoted curly '{'something'}' and this is <<not>> end";
System.out.println(input.replaceAll("(?<!')\\{(.*?)\\}(?!')", "<<$1>>")
.equals(output));
打印
true
关于java - 不受字符限制的字符串的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14354125/