Grainier
Grainier

Reputation: 1654

Escape a char which does not match a given regex pattern

I want to escape any single '{', '}' braces which do not match the pattern \{\{(.*?)}}. (i.e in {{{abc}} very first '{' should get escaped). Can someone please help me write a regex for this?

Upvotes: 2

Views: 36

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

NOTE: This will work in case you have no escape sequences in your input string.

You may create a "wrapper" regex to match and capture what you need to skip and add an alternative to what you need to replace. However, your regex is not suitable since it will match the whole {{{a}} as the first \{\{ will match the first {{ in the string. You need to replace the lazy dot matching with a negated character class [^{}]* to only match 0+ chars other than { and }.

Then just use Matcher#appendReplacement:

String s = "{{{abc}}";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(\\{\\{[^{}]*}})|[{}]").matcher(s);
while (m.find()) {
    if (m.group(1) != null) {
        m.appendReplacement(result, m.group(1));
    } else {
        m.appendReplacement(result, "\\\\" + m.group());
    }
}
m.appendTail(result);
System.out.println(result.toString()); // Demo output.

See the Java demo

Upvotes: 2

Anirudha
Anirudha

Reputation: 32797

The regex should be:

\{\{[^{}]+\}\}

Upvotes: 0

Related Questions