python.replace()正则表达式

2024-04-26 15:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在“<;/html>;”标记后抓取所有内容并将其删除,但我的代码似乎什么也没做。.replace()不支持regex吗?

z.write(article.replace('</html>.+', '</html>'))

Tags: 代码标记ltgt内容htmlarticlereplace
3条回答

@Ignácio是对的,+1,我只提供更多的例子。

要使用正则表达式替换文本,请使用re.sub函数:

sub(pattern, repl, string[, count, flags])

它将用作为string传递的文本替换pattern的非遍历实例。例如,如果需要分析匹配以提取有关特定组捕获的信息,可以将函数传递给string参数。more info here

示例

>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'

>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'

您可以对regex使用re模块,但是regex可能会对您想要的东西造成过度破坏。我可以试试

z.write(article[:article.index("</html>") + 7]

这比基于正则表达式的解决方案要干净得多,而且应该快得多。

没有。Python中的正则表达式由^{}模块处理。

article = re.sub(r'(?is)</html>.+', '</html>', article)

相关问题 更多 >