1

I'm agreed that regex is simple, but I really don't understand why it can't find and extract data. Also, I have very little experience with Java, may be it's the cause.

Method 1

String access_token = Utils.extractPattern(url, "access_token=([a-z0-9]+)&");

Url is like https://oauth.vk.com/blank.html#access_token=abcedefasdasdasdsadasasasdads123123&expires_in=0&user_id=1111111111

Utils

public static String extractPattern(String string, String pattern) {
    Pattern searchPattern = Pattern.compile(pattern);
    Matcher matcher = searchPattern.matcher(string);
    Log.d("pattern found - ", matcher.matches() ? "yes" : "no");
    return matcher.group();
}

Why it fails with java.lang.IllegalStateException: No successful match so far?

wapmorgan
  • 101
  • 1
  • 12
  • 1
    You have to call [`find`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#find--) first – Jorn Vernee Jul 14 '17 at 23:13
  • Call `matcher.group()` only when `matcher.matches()`. –  Jul 14 '17 at 23:19
  • Side note: you probably want `matcher.group(1)`. – shmosel Jul 14 '17 at 23:20
  • `matcher.matches()` will not match a substring like the OP wants. Use `matcher.find()` instead. https://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex – tima Jul 14 '17 at 23:20

1 Answers1

4

You need to use find() method of Matcher class to check whether the Pattern is found or not. Here's the documentation:

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Below should work:

public static String extractPattern(String string, String pattern) {
    Pattern searchPattern = Pattern.compile(pattern);
    Matcher matcher = searchPattern.matcher(string);
    if(matcher.find()){
        System.out.println("Pattern found");
        return matcher.group();
    }
    throw new IllegalArgumentException("Match not found");
}
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102