【问题标题】:python string parse with @ and space [closed]python字符串解析@和空格[关闭]
【发布时间】:2014-09-14 17:28:09
【问题描述】:

当用户在字符串中写入@ 表达式时,我想解析所有用户名。

例子:

I want to tell @susan and @rick that I love you all.

我想从字符串中得到['susan', 'rick'],解析表达式怎么写?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    为此写一个表达式并不难。

    >>> import re
    >>> re.findall(r'@(\S+)', ' I want to tell @susan and @rick that I love you all')
    ['susan', 'rick']
    

    或者使用匹配任意单词字符的\w

    >>> re.findall(r'@(\w+)', ' I want to tell @susan and @rick that I love you all')
    ['susan', 'rick']
    

    【讨论】:

    • 继续喂 :-)
    【解决方案2】:
    >>> import re
    >>> s = "I want to tell @susan and @rick that I love you all."
    >>> m = re.findall(r'@[a-z]+', s)
    >>> m
    ['@susan', '@rick']
    >>> 
    

    【讨论】:

      【解决方案3】:
      import re
      
      # input string
      myStr = "tell @susan and @rick that"
      
      # match
      names = re.findall(r"@(\w+)", myStr)
      

      【讨论】:

        【解决方案4】:

        使用正则表达式的答案也很有效。对于多样性,这里是一个列表比较。

        >>> s = 'I want to tell @susan and @rick that I love you all.'    
        >>> [i.strip('@') for i in s.split() if '@' in i]
        ['susan', 'rick']
        

        【讨论】:

        • 嗯,祝你好运,向你的老板解释这段代码。这似乎也总是生成一个垃圾字符串,这是第一个 @ 之前的部分。
        猜你喜欢
        • 2016-02-02
        • 1970-01-01
        • 1970-01-01
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        相关资源
        最近更新 更多