java - 不受字符限制的字符串的正则表达式模式

标签 java regex matcher

我需要不受字符限制的字符串的 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);

最佳答案

这是零宽度断言的一个明确用例。您需要的正则表达式不是很复杂:

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/

相关文章:

java - 将在 native 代码中缓存 jclass 防止类被卸载

regex - 使用 Ansible 从页面中提取过滤后的链接

java - 未使用 hibernate 序列ID生成器

java - 服务器-客户端应用程序中的 Spring Data 分页

javascript - 正则表达式:获取逗号之前最后一个字符出现之间的字符串

regex - 从括号内引用 data.table 列名称

java - 在一个匹配器中匹配多个属性

java - 如何在匹配器组而不是整个模式上追加替换?

Java 模式/匹配器 - 返回从一种方法到另一种方法的匹配

java - Gradle + TestNG:设置要运行的类