java - 为什么 Matcher 找不到模式

标签 java regex

<分区>

我同意正则表达式很简单,但我真的不明白为什么它不能找到和提取数据。另外,我对 Java 的经验很少,可能是这个原因。

方法一

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

网址类似于 https://oauth.vk.com/blank.html#access_token=abcedefasdasdasdsadasasasdads123123&expires_in=0&user_id=1111111111

工具

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

为什么失败并显示 java.lang.IllegalStateException: No successful match so far

最佳答案

您需要使用Matcher 类的find() 方法来检查是否找到了PatternHere's文档:

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.

下面应该可以工作:

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

关于java - 为什么 Matcher 找不到模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112752/

相关文章:

javascript - 字母数字的正则表达式,没有空格和 9 个字符输入?

java - 获取值的键而不是获取键值?

java - Spring-Boot 和 MySql 无法连接

java - 定时器功能未执行

java - JFileChooser getCurrentDirectory 返回错误的当前目录?

javascript - 从 html 字符串中删除样式

regex - WSO2 日志消息的 Logstash grok 模式

javascript - 从字符串中转义点,但在某些键旁边留下带有点的单词

java - ArrayIndexOutOfBoundsException :-1

javascript - 有人可以告诉我 jQuery rts 正则表达式中第二个捕获组的用途吗?