简体   繁体   English

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

[英]Regex pattern for string not bounded by character

I need java pattern for string not bounded by a character. 我需要java模式的字符串不受字符限制。

I have a string (as mentioned below), with some curly brackets bounded by single quotes and other curly brackets that are not. 我有一个字符串(如下所述),其中一些大括号由单引号和其他大括号括起来。 I want to replace the curly brackets that are not bounded by single quotes, with another string. 我想用另一个字符串替换不受单引号限制的大括号。

Original string: 原始字符串:

this is single-quoted curly '{'something'}' and this is {not} end

Needs to be converted to 需要转换为

this is single-quoted curly '{'something'}' and this is <<not>> end

Notice that the curly brackets { } that are not bounded by single quotes have been replaced with << >>. 请注意,不受单引号限制的大括号{}已替换为<< >>。

However, my code prints (character gets eaten up) the text as 但是,我的代码打印(字符被吃掉)文本为

this is single-quoted curly '{'something'}' and this is<<no>> end

when I use the pattern 当我使用模式

[^']([{}])

My code is 我的代码是

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

This is a clear use case for zero-width assertions. 这是零宽度断言的明确用例。 The regex you need isn't very complex: 你需要的正则表达式并不复杂:

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

prints 版画

true

使用Java Pattern文档的特殊构造部分中的否定先行/ lookbehind构造。

Try this : 尝试这个 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM