Unmatch escaped braces

Viewed 32

Which regular expression can I use to find all }, all while excluding escaped \}? I.e. how do I get as only match:

{Hello \} world}
               ^
2 Answers

The following pattern should achieve your goal:

(?<!\\)\}

The pattern you're looking for is (?<!...):

Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion.

In contrast to Amirhossein Kiani's suggestion, the match does not include the preceding character, but only the closing bracket. To illustrate:

{Hello \} world}
               ^ with negative lookbehind
{Hello \} world}
              ^^ with Amirhossein Kiani's suggestion

Note: When working with regular expressions in Python, please study the documentation. Many simple questions like this could be avoided.

You can try the pattern below:

[^\\](?P<bracket>})

Note that, this will select all } that do not have a \ before them, but any other character will be selected. You can try.group function giving bracket as an argument to select the bracket.

To have a better understanding, take a look at this link

Update

Personally speaking, I prefer Green绿色's answer since it just selects the desired bracket.

Related