Regex match any setence containing ^ except those that start with \

Solution 1:

You can use

import re
texts = [r'foo^2', r'\foo^2']
for text in texts:
    print(re.sub(r'(?<!\\)((?:\\\\)*\b\w+)\^(\w+)', r'$\1^\2$', text))

See the Python demo.

Output:
$foo^2$
\foo^2

See the regex demo. Details:

  • (?<!\\) - a location not immediately preceded with aa \ char
  • ((?:\\\\)*\b\w+) - Group 1: zero or more \\ string occurrences, a word boundary and one or more word chars
  • \^ - a ^ char
  • (\w+) - Group 2: one or more word chars.