I want to build a regex that will match all unescaped $
in strings that represents a regex.
In this case, a character is unescaped if it contains an equal number of backslashes behind it (each pair of backslashes means the backslash char itself, and therefore the next character isn't escaped).
I came up with this pattern:
(?<!\\)(\\{2})*\$
Explanation: although this will also match the backslashes preceding the $
, this is the closest I came to a solution. This assures an equal number of backslashes before a $
which is not preceded by another backslash, making an odd number of backslashes.
My issues is that it seems that I need 2 consecutive non consuming groups to make the total number of backslashes even, but this is not possible. Is there another way to make that?
Make the repeating group non-capturing, and add the meta escape \K
.
/(?<!\\)(?:\\{2})*\K\$/g
Here it is on Regex101.