Why Matcher doesn't find pattern [duplicate]

谁说我不能喝 提交于 2021-01-28 09:51:05

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/45112752/why-matcher-doesnt-find-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!