Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式:使用System.out.println(m.matches())时,并非所有匹配项都会打印出来;_Java - Fatal编程技术网

Java 正则表达式:使用System.out.println(m.matches())时,并非所有匹配项都会打印出来;

Java 正则表达式:使用System.out.println(m.matches())时,并非所有匹配项都会打印出来;,java,Java,我执行以下代码: public static void test() { Pattern p = Pattern.compile("BIP[0-9]{4}E"); Matcher m = p.matcher("BIP1111EgjgjgjhgjhgjgjgjgjhgjBIP1234EfghfhfghfghfghBIP5555E"); System.out.println(m.matches()); while(m.find()) { System.out.println(m.gro

我执行以下代码:

public static void test() {
 Pattern p = Pattern.compile("BIP[0-9]{4}E");

 Matcher m = p.matcher("BIP1111EgjgjgjhgjhgjgjgjgjhgjBIP1234EfghfhfghfghfghBIP5555E");
 System.out.println(m.matches());
 while(m.find()) {
  System.out.println(m.group());
 }
}

我无法解释的是,代码是在何时使用System.out.println(m.matches())执行的打印的匹配项为:BIP1234EBIP555E。 但是当System.out.println(m.matches())时从代码中删除,匹配BIP11111E也会打印出来


有人能解释一下这是怎么可能的吗?非常感谢您的帮助。

Java中的Matcher维护给定字符串中找到的组的索引

例如,在示例中提供的字符串中-bip11111egjjhgjhgjhjbip1234efghfhfghfghhbip5555e

共有3组符合该模式

BIP11111E BIP1234E BIP555E

创建匹配器时,它从索引0开始。当我们使用m.find()迭代匹配器时,每次它找到一个模式时,它都会标记找到的模式的索引位置

例如,第一个gourp位于字符串的开头-也就是说,它从0开始,一直到字符串的第7个(基于0的索引)字符。下次我们说find()时,它从第8个字符开始查找模式的下一个匹配项

m、 matches尝试匹配整个字符串,它还处理内部索引


在使用m.find()进行迭代之前调用m.matches()时,索引将从初始值0移动。因此,如果调用m.matches(),将跳过第一组BIP11111E。

您可以使用
Matcher.reset
方法在调用
matches
后将匹配器重置为其初始状态。该方法更改matcher对象的当前状态,在下一次调用
find
时,它开始查找第一个
g
字符。

这个问题有点让人困惑,我想你的意思是在你的第二句话中引用System.out.println(m.group())@karianna不,这并不让人困惑。如果之前调用了
matches
,则最后两个匹配项将打印在循环中。@khachik-你说得对-Devxx;之后眼睛疲劳)