开发者

replace an item in a html tag spanning multiple lines

I have a text file with html:

Blah, blah, blah

some text is here.

<div> something here

something else </body></html>

so far, if the tags are on one line this works:

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

text = textfile.read()

a = re.search('<div.+?<\/html>开发者_如何转开发;', text)

repstr = c.group(0)

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

works fine, I don't have nested tags. But if the tags are on multiple lines, like the first example, it doesn't work! what can I use to test multiple lines?


By default, the dot doesn't match new lines. To make it match new lines, you need to compile the regex with the flag re.DOTALL, eg:

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

That being said, you really shouldn't use regex to parse HTML.

Do yourself a favor and use an XML parser like BeautifulSoup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜