简单的 Java 正则表达式匹配器不起作用

2024-04-25

Code :

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

Error :

Exception in thread "main" java.lang.IllegalStateException: No match found

我在这里做错了什么?


你需要打电话find() http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find%28%29 on the Matcher在你打电话之前group()以及查询匹配文本或操作它的相关函数(start(), end(), appendReplacement(StringBuffer sb, String replacement), etc.).

所以在你的情况下:

if (m.find()) {
    System.out.println("id = " + m.group(1));
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

简单的 Java 正则表达式匹配器不起作用 的相关文章

随机推荐