【问题标题】:How to extract usernames out of Tweets?如何从推文中提取用户名?
【发布时间】:2010-10-18 22:36:57
【问题描述】:

我有以下示例推文:

RT @user1: who are @thing and @user2?

我只想拥有user1thinguser2

我可以使用什么正则表达式来提取这三个名称?

PS:用户名只能包含字母、数字和下划线。

【问题讨论】:

    标签: regex twitter


    【解决方案1】:

    测试:

    /@([a-z0-9_]+)/i
    

    在 Ruby (irb) 中:

    >> "RT @user1: who are @thing and @user2?".scan(/@([a-z0-9_]+)/i)
    => [["user1"], ["thing"], ["user2"]]
    

    在 Python 中:

    >>> import re
    >>> re.findall("@([a-z0-9_]+)", "RT @user1: who are @thing and @user2?", re.I)
    ['user1', 'thing', 'user2']
    

    在 PHP 中:

    <?PHP
    $matches = array();
    preg_match_all(
        "/@([a-z0-9_]+)/i",
        "RT @user1: who are @thing and @user2?",
        $matches);
    
    print_r($matches[1]);
    ?>
    
    Array
    (
        [0] => user1
        [1] => thing
        [2] => user2
    )
    

    【讨论】:

    • 您必须在 [a-z0-9_] 周围添加一个捕获组,即 @([a-zA-Z0-9_]+)
    • 谢谢,它工作正常!最后一个问题:当“@”之前必须有空格或必须在开头时,我可以使用以下表达式吗? "/( |^)@([a-z0-9_]+)/i"
    • 你也可以使用单词边界 \b => /\b@([a-z0-9_]+)/i
    【解决方案2】:

    用这个正则表达式尝试迭代器(findall):

    (@[\w-]+)
    

    再见

    【讨论】:

    • 简单...不错!结合 scan (ruby) 得到一个匹配数组: text.scan(/@[\w-]+/)
    【解决方案3】:
    /(?<!\w)@(\w+)/
    

    以上内容涵盖了以下场景,该线程中的其他答案没有:

    • 不应作为用户名的 @ 符号,例如“我的电子邮件是 test@example.com”
    • 仍然允许在字符串开头的用户名,例如"@username lorem ipsum..."

    【讨论】:

    • 谢谢。没有人考虑过电子邮件地址问题!
    【解决方案4】:

    在您的项目中包含 twitter 文本库 [1] 来解决此文本问题是个好主意。

    twttr.txt.extractMentions("a very generic twitt with some @mention");
    

    [1]https://github.com/twitter/twitter-text-js

    【讨论】:

      【解决方案5】:

      应该这样做(为方便起见,我使用了命名捕获):

      .+?@(?[a-zA-Z0-9_]+):[^@]+?@(?[^\s]+)[^@]+?@(?[a-zA -Z0-9_]+)

      【讨论】:

      • 当我使用您的表达式时,PHP 会显示一条错误消息。诸如“缺少分隔符 . 在末尾”之类的东西。
      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2017-01-11
      • 2020-08-24
      • 2016-01-07
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多