DopeDod DopeDod - 1 month ago 8
Java Question

Java parsing mentions from tweet

i'm trying to parse username mentions from specific tweet using regex, but it always returns IllegalStateException that match is not found but i know that regex is good as it works for others http://shahmirj.com/blog/extracting-twitter-usertags-using-regex found it on this site.

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));


Could you help me to find mistake here ? Or should I used different regex

Answer

You forgot to call find(), which is one of the matching methods, as documented in the 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));
}

I also did a small tweak on the regex, as the + after [A-Za-z] seemed pointless.

Comments