有如下目标串和模式串
目标串:10,20,30,40,50
模式串:(\d+),(\d+)
当我们去匹配该目标串时,第一个匹配到的大组应该是10,20
,然后是10
和20
两个小组对吧?
- 请务必在调用
group
之前调用find
方法,相当于查找之后才会有组,否则会报错No match found
Matcher matcher = Pattern.compile("(\\d+),(\\d+)").matcher("10,20,30,40,50");
matcher.find(); // 这一行必须有,否则调用 group 报错
System.out.println(matcher.group());
-
group()默认返回的是第0组,该组不是第一个括号的捕获,而是整个匹配到的子串,例如在执行一次find()后matcher.group(0)和matcher.group()都返回
10,20
从第1组开始才是括号内捕获的内容
-
每一次调用find都会匹配到下一个大组,例如调用2次find匹配到的group就是
30,40