简单的Java正则表达式匹配器无法正常工作
发布时间:2020-05-26 03:54:12 所属栏目:Java 来源:互联网
导读:代码: import java.util.regex.*;public class eq { public static void main(String []args) { String str1 = some=StringHeremodelId=324; Pattern rex = Pattern.compile(.*modelId=([0
|
代码: 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 我在这做错了什么? 解决方法您需要在Matcher上调用find(),然后才能调用group()和相关函数来查询匹配的文本或对其进行操作(start(),end(),appendReplacement(StringBuffer sb,String replacement)等).
所以在你的情况下: if (m.find()) {
System.out.println("id = " + m.group(1));
}
这将找到第一个匹配(如果有)并提取与正则表达式匹配的第一个捕获组.如果要在输入字符串中查找所有匹配项,请将if更改为while循环. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
