Why does regex require triple backslash to match a single backslash?

462 views Asked by At

I was trying to match a backslash using regex and thought that this could be done by using two double backslashes, using the former to escape the latter. However, when I run the code


path_str = r"\Animal_1-"
Match_backslash = re.search("[\\]", path_str)
print(Match_backslash)

I get the error message:

error: unterminated character set at position 0

But, when I use triple backslash:


path_str = r"\Animal_1-"
Match_backslash = re.search("[\\\]", path_str)
print(Match_backslash)

it for some reason works, can anyone explain why triple backslash is needed and why double backslash isn“t sufficient?

0

There are 0 answers