【发布时间】:2019-06-28 16:25:19
【问题描述】:
我正在浏览网站以查找特定字词。我使用带有 bs4 的 re.compile 来搜索这个词。如果我的单词包含反斜杠 ('\'),我会遇到问题。我希望我能在如何做到这一点上得到一些帮助。我的代码通常是这样的
results = self.soup.find_all(string=re.compile('.*{0}.*'.format(searched_word), re.IGNORECASE), recursive=True)
当我尝试使用searched_word = Software\Microsoft\Windows\CurrentVersion\Run 时,此代码会引发re.error: bad escape \M at position 13 错误
我在某处读到,为了逃避反斜杠,我应该将其设为Software\\Microsoft\\Windows\\CurrentVersion\\Run,这会引发错误。或者 Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run 不会抛出错误但不会返回文本。
【问题讨论】:
-
使用
re.escape()? docs.python.org/3.6/library/re.html#re.escape -
然后我写答案,您可以接受并关闭问题。
标签: regex python-3.x beautifulsoup