0

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

DopeDod
  • 27
  • 2
  • 5

2 Answers2

0

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.

janos
  • 120,954
  • 29
  • 226
  • 236
0

From the javadoc:

The explicit state of a matcher is initially undefined; attempting to query any part of it before a successful match will cause an IllegalStateException to be thrown. The explicit state of a matcher is recomputed by every match operation.

You have to call matcher.matches() before calling matcher.group(0)

StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31