【问题标题】:Can't delete white space in a substring thorugh regular expression in python 3x无法通过python 3x中的正则表达式删除字符串中的空格
【发布时间】:2016-02-22 17:04:12
【问题描述】:

我的字符串是一些垃圾 13245 65798 username@hostname.com 和其他垃圾文本。 我想通过正则表达式分隔 13245 65798usernamehostname.com 。 我使用搜索功能,但我遇到了空白问题。 当我尝试分离这个 13245 65798 子字符串时,一个额外的 white space 留在分离后。

我的代码

>>> m =  re.search('(\d[\s\d]+)([\w]+)@([\w.]+)','Some garbage 13245 65798 username@hostname.com and others garbage texts.')

输出

>>> m.groups()
('13245 65798 ', 'username', 'hostname.com')
             ^  

这里是额外的空白。 我怎样才能删除那个空间?

【问题讨论】:

  • 事后直接strip()不是更方便吗?
  • s='Some garbage 13245 65798 username@hostname.com and others garbage texts.'; re.findall('(\d+\s\d+) (\w+)@(\w+.com)', s) 可能是我能想到的最干净的正则表达式。
  • 您获得额外空白的原因是[\s\d] 将匹配任何作为分隔符或数字的字符。你的意思可能是(\d+\s\d+),或者更简单的(\d+ \d+)

标签: python regex string python-3.x search


【解决方案1】:
m =  re.search('(\d+(?:\s*\d+)*)\s*([\w]+)@([\w.]+)','Some garbage 13245 65798 username@hostname.com and others garbage texts.')

这应该会为您完成。请参阅演示。

https://regex101.com/r/hE4jH0/14

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多