【问题标题】:Remove all whitespaces in URL/Email [closed]删除 URL/电子邮件中的所有空格 [关闭]
【发布时间】:2018-09-11 02:34:31
【问题描述】:

我想删除 URL/电子邮件地址中的所有空格。地址位于“普通”字符串中,例如:"Today the weather is fine. Tomorrow, we'll see. More information: www.weather .com or info @weather.com"

我正在寻找一个好的正则表达式(使用 Python 的 re 模块),但我的版本无法处理所有情况

re.sub(u'(www)([ .])([a-zA-Z\-]+)([ .])([a-z]+)', '\\1.\\3.\\5')

【问题讨论】:

  • 预期输出是什么?
  • 你不能用replace吗? "https://www . some-example.c o m".replace(' ', '')

标签: python regex removing-whitespace


【解决方案1】:

您的 url 表达式只需要稍作修正。电子邮件的正则表达式也可以从 url 表达式继承。

>>> #EXPRESSIONS:
>>> url = "(www)+([ .])+([a-zA-Z\-]+)+([ .])+([a-z]+)"
>>> ema = "([a-zA-Z]+)+([ +@]+)+([a-zA-Z\-]+.com)"
>>> 
>>> #IMPORTINGS:
>>> import re
>>> 
>>> #YOUR DATA:
>>> string = "Today the weather is fine. Tomorrow, we'll see. More information: www.weather .com or info @weather.com"
>>> 
>>> #Scraping Data
>>> "".join(re.findall(url,string)[0])
'www.weather.com'
>>> "".join(re.findall(ema,string)[0]).replace(" ","")
'info@weather.com'
>>> 

【讨论】:

  • 非常感谢!你的回答很有帮助!最后一个问题:如果我想在普通文本中向“/”添加空格,而不是在 URL 中,我可以使用什么正则表达式。示例:“女士们/先生们您好。您可以在 www.skynews.com/today/act 上找到更多信息。” --> “女士们/先生们,您好。您可以在 www.skynews.com/today/act 找到更多信息。”
  • @StMan 你可以接受我的回答。如果您的 URL 不包含空格,那么这将起作用:(www.)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w]*)
猜你喜欢
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
相关资源
最近更新 更多