【问题标题】:Everything after/before regex in PythonPython中正则表达式之后/之前的所有内容
【发布时间】:2014-10-10 18:53:54
【问题描述】:

我有多个具有下一个结构的字符串实例:

RT @username: Tweet text

我需要捕获用户名(以便稍后构建网络)。 到目前为止,我有这个:

re.findall('\@(.*)') 

它应该在'@'之后得到所有东西,但我很难弄清楚如何在(不包括)':'之前得到所有东西。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    要获取@: 之间的所有内容,您可以使用以下模式:

    @([^:]+)
    

    以下是其匹配项的细分:

    @      # @
    (      # The start of a capture group
    [^:]+  # One or more characters that are not :
    )      # The close of the capture group
    

    这是一个演示:

    >>> from re import findall
    >>> mystr = '''\
    ... RT @username: Tweet text
    ... RT @abcde: Tweet text
    ... RT @vwxyz: Tweet text
    ... '''
    >>> findall('@([^:]+)', mystr)
    ['username', 'abcde', 'vwxyz']
    >>>
    

    【讨论】:

    • 经过大量这样的回答,你的回答奏效了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    相关资源
    最近更新 更多