我需要不受字符限制的字符串的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, "&lt;&lt;"); } else if ( "}".equals(matcher.group(1))) { matcher.appendReplacement(strBuffer, "&gt;&gt;"); }}matcher.appendTail(strBuffer); (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 这是零宽度断言的明确用例。您需要的正则表达式不是很复杂: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 (adsbygoogle = window.adsbygoogle || []).push({});
10-05 20:42
查看更多