用Java构造正则表达式

时间:2013-07-03 20:45:03

标签: java regex

我已经在线阅读了几个关于Java正则表达式的教程,但我仍然发现构造正则表达式非常困难。

示例文本(推文):

@HIMYM_CBS: Barney Stinson. That Guy's Awesome

另一个样本:

Barney Stinson.  @HIMYM_CBS: That Guy's Awesome

这是HIMYM_CBS的推文。

我想要完成的是,在任何推文的情况下,我想知道该推文是否针对任何人(例如HIMYM_CBS)。无论是谁,都无所谓。

我的问题是:那么构建正则表达式以实现这个目标应该是什么样的思路呢?

推文存储为字符串:

String Tweet = "@HIMYM_CBS: Barney Stinson. That Guy's Awesome";

5 个答案:

答案 0 :(得分:4)

Twitter用户名长度最多为15个字符,以@开头,只能包含字母数字和下划线。

所以你想要使用的正则表达式是:

(?<=\s|\A)@(\w{1,15})
^   ^ ^^ ^^^^ ^     ^ ")" ends a matching group.
|   | || |||| | matches preceding expression between 1 and 15 times.
|   | || |||| "\w" matches [a-zA-Z0-9_]
|   | || ||| "(" begins a matching group
|   | || || literal "@"
|   | || | ")" ends the zero-width lookbehind assertion
|   | || "\A" will match the beginning of the string
|   | | "|" denotes that either this or that matches
|   | "\s" matches a space character
| "(?<=" is the beginning of a zero-width lookbehind assertion

答案 1 :(得分:2)

正则表达式

@\\w+

工作?

答案 2 :(得分:1)

String tweet = "@HIMYM_CBS: Barney Stinson. That Guy's Awesome";
Pattern p = Pattern.compile("@(\\w+)");
Matcher m = p.matcher(tweet);
if (m.find()) {
  System.out.println(m.group(1));
} else {
  System.out.println("not found.");
}

也许您想查看Pattern类的api文档。

代码中\w表示相当于[a-zA-Z_0-9]的单词字符。

答案 3 :(得分:1)

/(?:^|(?<=\s))@([A-Za-z_0-9]+)(?=[.?,:]?\s)/
  

您只能在Twitter句柄中使用字母,数字或下划线符号(_)。

示例测试用例
@This(在一行开头匹配)正则表达式忽略@ this ,但匹配@separate令牌以及句子末尾的标记@this 。还是@this? (不选择.?)和@this:和@this,如直接消息SO样式。是的,推文中的任何 email@address.com 也会被忽略。

匹配@时的正则表达式还可以让您快速访问userid之后的内容(如@userid中的Matcher#group(1)),方法是从{{1}}中选择它。

答案 4 :(得分:0)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String Tweet = "@HIMYM_CBS: Barney Stinson. That Guy's Awesome";
        String regex = "@([^:]+)";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(Tweet);
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }

    }

}

输出:HIMYM_CBS