【问题标题】:Python: How to exclude a group of characters before a specific character in a fixed stringPython:如何在固定字符串中的特定字符之前排除一组字符
【发布时间】:2014-02-26 15:34:18
【问题描述】:

使用 python 脚本,我想从用户列表中排除“@”处和之前的所有字符*。我只想查看完整的域名。 我尝试使用正则表达式、替换、子字符串、自定义函数等来实现这一点……但没有任何东西可以生成我需要的输出。 我觉得我在寻找错误的方向,我一定错过了一些简单的东西。

*用户列表:

user@domain.com
anotheruser@somedomain.org
superuser@domains.co.uk
foo@domain.com

【问题讨论】:

  • 是的,你可以考虑split()
  • 我将如何使用拆分?与子字符串一起使用?用户列表在我的脚本中生成如下:domain = temp[1].split()[0].strip()

标签: python regex string character


【解决方案1】:
email = 'user@domain.com'
_, domain = email.split('@')
print domain

>>> domain.com

【讨论】:

    【解决方案2】:

    为了完整起见,这里是 (a) 使用正则表达式的解决方案:

    >>> import re    
    >>> re.search(r'(?<=@).*', 'me@example.com').group()
    'example.com'
    

    【讨论】:

    • @py_newby:在调用group() 之前先检查匹配可能是个好主意。如果您的输入包含格式错误的电子邮件,例如"me&amp;#64;example.com",那么re.search() 将返回None。当然调用None.group() 会给你一个错误;)
    【解决方案3】:

    作为 split() 的替代方法,您可以按如下方式对索引进行切片

    email = 'user@domain.com'
    domain = email[email.index['@']+1:]
    print domain
    
    >>> domain.com
    

    【讨论】:

      【解决方案4】:

      这是@chishaku 答案的一个稍微安全的版本;它返回目标字符或子字符串第一次出现之后的所有内容,并且不会因 0 次或多次出现而窒息。

      def after_first(ch, s):
          return s.split(ch, 1)[-1]
      
      for user in userlist:
          print after_first("@", user)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        • 2015-01-26
        • 2016-08-30
        • 2015-09-05
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多