【问题标题】:replace an item in a html tag spanning multiple lines替换跨越多行的 html 标记中的项目
【发布时间】:2010-09-08 01:50:41
【问题描述】:

我有一个带有 html 的文本文件:

Blah, blah, blah

some text is here.

<div> something here

something else </body></html>

到目前为止,如果标签在一行上,这是可行的:

textfile = open("htmlfile.txt", "r+")

text = textfile.read()

a = re.search('<div.+?<\/html>', text)

repstr = c.group(0)

text = text.replace(repstr, '', 1)

工作正常,我没有嵌套标签。 但是如果标签在多行上,就像第一个例子一样,它就不起作用!我可以用什么来测试多行?

【问题讨论】:

    标签: python regex replace


    【解决方案1】:

    默认情况下,点不匹配新行。要使其匹配新行,您需要使用标志re.DOTALL 编译正则表达式,例如:

    a = re.search('<div.+?<\/html>', text, re.DOTALL)
    

    话虽如此,你真的shouldn't use regex to parse HTML.

    帮自己一个忙,使用像 BeautifulSoup 这样的 XML 解析器。

    【讨论】:

    • 哦,我明白了。我的项目相当简单,并不需要 Beautifulsoup,但请记住这一点。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 2014-08-04
    • 2023-03-15
    • 2017-11-05
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多