在python中的一行代码中替换字符串中的多个链接

时间:2015-10-08 13:19:21

标签: python regex

我是正则表达式模块的新手。我试图删除给定exampleString中的所有链接,但是在一行代码中删除:

exampleSentence = exampleSentence.replace(link for link in re.findall(r'http://*',exampleSentence),'')

但我收到此语法错误:

SyntaxError: Generator expression must be parenthesized if not sole argument

如何处理?

2 个答案:

答案 0 :(得分:4)

你有很多问题。

首先,str.replace()在给定字符串中用另一个替换子字符串;它不需要发电机。

示例:

print 'example'.replace('e', 'E')

接下来,如果您要删除,则有re.sub()

data = re.sub(
  r'[A-Za-z]+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&;\?#/.=]+', # the URI
  '', # the replacement (nothing here)
  input_data
)

URI正则表达式是从@miko-trueman answer复制的。

答案 1 :(得分:2)

如果您只想删除字符串中的所有链接,则不需要生成器。以下将有效。

import re
exampleString = "http://google.com is my personal library. I am not one for http://facebook.com, but I am in love with http://stackoverflow.com"
exampleString = re.sub(r"(?:\@|https?\://)\S+", '', exampleString)