简单的Java正则表达式匹配器无法正常工作

viv*_*vek 6 java regex

代码:

import java.util.regex.*;

public class eq {
    public static void main(String []args) {
        String str1 = "some=String&Here&modelId=324";
        Pattern rex = Pattern.compile(".*modelId=([0-9]+).*");
        Matcher m = rex.matcher(str1);
        System.out.println("id = " + m.group(1));
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

Exception in thread "main" java.lang.IllegalStateException: No match found
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

nha*_*tdh 19

你需要调用find()Matcher,然后才能调用group()和查询有关匹配文本相关功能或操纵它(start(),end(),appendReplacement(StringBuffer sb, String replacement)等).

所以在你的情况下:

if (m.find()) {
    System.out.println("id = " + m.group(1));
}
Run Code Online (Sandbox Code Playgroud)

这将找到第一个匹配(如果有)并提取与正则表达式匹配的第一个捕获组.如果要在输入字符串中查找所有匹配项,请更改ifwhile循环.