我需要java模式用于不受字符限制的字符串。
我有一个字符串(如下所述),其中一些花括号由单引号和其他大括号括起来。我想用另一个字符串替换不受单引号限制的花括号。
原始字符串:
this is single-quoted curly '{'something'}' and this is {not} end
需要转换为
this is single-quoted curly '{'something'}' and this is <<not>> end
请注意,不受单引号限制的大括号{}已替换为&lt;&lt; &GT;&GT;
然而,我的代码打印(字符被吃掉)文本为
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);
答案 0 :(得分:3)
这是零宽度断言的明确用例。你需要的正则表达式并不复杂:
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
答案 1 :(得分:1)
使用Java the special constructs section文档的Pattern
中的否定先行/ lookbehind构造。
答案 2 :(得分:0)
试试这个:
String regex = "([^'])([{}])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
if ("{".equals(matcher.group(2))) {
matcher.appendReplacement(strBuffer, matcher.group(1) + "<<");
} else if ("}".equals(matcher.group(2))) {
matcher.appendReplacement(strBuffer,matcher.group(1) + ">>");
}
}
matcher.appendTail(strBuffer);