【问题标题】:How to search using backslash如何使用反斜杠进行搜索
【发布时间】: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 不会抛出错误但不会返回文本。

【问题讨论】:

标签: regex python-3.x beautifulsoup


【解决方案1】:

您似乎没有转义re.compile() 的字符串。为此,请使用re.escape() (doc):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-28
    • 2011-09-06
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多