如何在Python中删除字符串中的任何URL

2024-09-30 02:24:06 发布

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

我要删除字符串中的所有URL(将它们替换为“”) 我到处找,但找不到我想要的。

示例:

text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/

我希望结果是:

text1
text2
text3
text4
text5
text6

Tags: 字符串comhttpurl示例text1text2text4
3条回答

最短的路

re.sub(r'http\S+', '', stringliteral)

这对我有效:

import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"

URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string

结果:

text1
text2

text3
text4

text5
text6

Python脚本:

import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)

输出:

text1
text2
text3
text4
text5
text6

测试此代码here

相关问题 更多 >

    热门问题