【问题标题】:Java parsing mentions from tweet [duplicate]Java解析推文中的提及[重复]
【发布时间】:2017-03-12 07:52:50
【问题描述】:

我正在尝试使用正则表达式从特定推文中解析用户名提及,但它总是返回未找到匹配的 IllegalStateException 但我知道正则表达式很好,因为它适用于其他人 http://shahmirj.com/blog/extracting-twitter-usertags-using-regex found它在这个网站上。

    String input = "@rivest talk in 30 minutes #hype";
    String regex = "(?<=^|(?<=[^a-zA-Z0-9-_\\\\.]))@([A-Za-z]+[A-Za-z0-9_]+)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    System.out.println(matcher.group(0));

你能帮我找出这里的错误吗?或者我应该使用不同的正则表达式

【问题讨论】:

    标签: java regex twitter


    【解决方案1】:

    您忘记调用find(),这是匹配方法之一,如javadoc 中所述。

    String input = "@rivest talk in 30 minutes #hype";
    String regex = "(?<=^|(?<=[^a-zA-Z0-9-_\\\\.]))@([A-Za-z][A-Za-z0-9_]+)";
    Matcher matcher = Pattern.compile(regex).matcher(input);
    if (matcher.find()) {
        System.out.println(matcher.group(0));
    }
    

    我还对正则表达式做了一些小调整,因为[A-Za-z] 之后的+ 似乎毫无意义。

    【讨论】:

      【解决方案2】:

      来自the javadoc

      匹配器的显式状态最初是未定义的;试图 在成功匹配之前查询它的任何部分将导致 抛出 IllegalStateException。匹配器的显式状态是 由每个匹配操作重新计算。

      您必须先致电matcher.matches(),然后再致电matcher.group(0)

      【讨论】:

        猜你喜欢
        • 2012-02-14
        • 2013-02-19
        • 2011-06-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 2017-10-04
        • 2021-10-04
        • 2012-12-25
        相关资源
        最近更新 更多