1

文字で区切られていない文字列の 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);
4

3 に答える 3

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
于 2013-01-16T08:53:34.950 に答える
1

Javaドキュメンテーションの特別な構成セクションから、否定先読み/後読み構成を使用します。Pattern

于 2013-01-16T08:36:46.623 に答える
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);
于 2013-01-16T08:51:41.870 に答える