# Why backward slash

My Code:

email_mentions = titles.str.contains(r"\be[-\s]?mails?\b", flags=re.I).sum()

What I expected to happen:

What actually happened:



pattern = r"\be[-\s]?mails?\b"
email_mentions = titles.str.contains(pattern, flags=re.I).sum()


<!--My code perfectly works but I don't get why the solution code has another backward slash just after the bracket ([\-\]): -->
1 Like

In this case, you’re right because the hyphen has no special meaning in the regex. BUT if there was a regex like [a-z] that would match any letter from a to z , you would escape the hyphen if you wanted your regex to match a , - or z` . Hope it helps!

Happy coding:)
Artur

3 Likes