How to search using backslash

Viewed 80

I'm working to look through websites to find specific words. I use the re.compile with bs4 to search for the word. I am having issues if my word contains a backslash ('\'). I was hoping I could get some help on how to do this. My code is usually like this

results = self.soup.find_all(string=re.compile('.*{0}.*'.format(searched_word), re.IGNORECASE), recursive=True)

This code throws an error of re.error: bad escape \M at position 13 when I try to have searched_word = Software\Microsoft\Windows\CurrentVersion\Run

I read somewhere that in order to escape backslash, I should make it Software\\Microsoft\\Windows\\CurrentVersion\\Run which throws an error. Or Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run which doesn't throw an error but does not return the text.

1 Answers

It seems you are not escaping the string for re.compile(). To do that, use re.escape() (doc):

results = self.soup.find_all(string=re.compile('.*{0}.*'.format(re.escape(searched_word)), re.IGNORECASE), recursive=True)
Related