Python regex question

Hey guys. Just have a quick question with python regex

How do I match the string “C++”? Because the “++” is causing me an error saying “error: multiple repeat” as if it’s taking the “++” as pattern argument, rather than the actual string

The + is a reseved character in regex, meaning match the previous character 1 or more times.

In order to match a + literally you’d need to escape it: C\\+\\+

If you don’t know what you’d need to match beforehand you can use re.escape, that would turn C++ into C\\+\\+ for you.

With python regex using a literal string, it is best practice to use a raw string:

r'C\+\+'

will DTRT, make it much more readable, potentially saving you from escape hell.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.