代码:
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));
}
}
错误:
Exception in thread "main" java.lang.IllegalStateException: No match found
我在这里做错了什么?
最佳答案
您需要调用find()
在 Matcher
之前,您可以调用 group()
和查询匹配文本或对其进行操作的相关函数(start()
,end()
、appendReplacement(StringBuffer sb, String replacement)
等。
所以在你的情况下:
if (m.find()) {
System.out.println("id = " + m.group(1));
}
这将找到第一个 匹配项(如果有)并提取正则表达式匹配的第一个捕获组。如果要查找输入字符串中的所有匹配项,请将 if
更改为 while
循环。
关于java - 简单的 Java 正则表达式匹配器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153146/