【问题标题】:Regex pattern for string not bounded by character字符串的正则表达式模式不受字符限制
【发布时间】:2013-01-16 08:33:21
【问题描述】:

我需要不以字符为界的字符串的 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);

【问题讨论】:

    标签: java regex matcher


    【解决方案1】:

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

    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,感谢您指出我(现已删除)答案中的缺陷。
    • 非常感谢,这很有帮助
    • 对不起大家,无法对答案投票(说......没有足够的声誉)。对“这篇文章对您有用吗?”的回答是肯定的。问题。
    【解决方案2】:

    使用 Java Pattern 文档的 the special constructs section 中的否定前瞻/后瞻结构。

    【讨论】:

    • 一种“更简单”的方法是在替换字符串中使用捕获组和反向引用。
    • @nhahtdh 是的,但我不会说那更简单,我会说它更混乱。如果可能的话,我喜欢将所有模式匹配放入模式中,而不是放入处理逻辑中。
    • 它“更简单”(引用),因为它可能并不适用于所有人。当然,就我个人而言,我会使用环视。
    【解决方案3】:

    试试这个:

    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);
    

    【讨论】:

    • 感谢指正。我尝试了一些 regex-s 不成功,但这很棒。 :)
    猜你喜欢
    • 2019-11-09
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多