-3

是否有可能在一行中有两个或多个字符与模式匹配,我们只打印该行一次?

例如:

    Matcher matcher = Pattern.compile(("V+N+PN+")).matcher(line);

    while (matcher.find()) {
        System.out.println(matcher);
        System.out.println(line);
    }

输出:

java.util.regex.Matcher[pattern=V+N+PN+ region=0,34 lastmatch=VVNNNNNNNNNPNNNN]
NVNVVNNNNNNVVNNNNNNNNNPNNNNPNNONNN
java.util.regex.Matcher[pattern=V+N+PN+ region=0,42 lastmatch=VVNPNNN]
OSNVVNPNNNVNVNNVVNNPNNNNNNNNPVNNNPNNNPNNNO
java.util.regex.Matcher[pattern=V+N+PN+ region=0,42 lastmatch=VVNNPNNNNNNNN]
OSNVVNPNNNVNVNNVVNNPNNNNNNNNPVNNNPNNNPNNNO
java.util.regex.Matcher[pattern=V+N+PN+ region=0,42 lastmatch=VNNNPNNN]
OSNVVNPNNNVNVNNVVNNPNNNNNNNNPVNNNPNNNPNNNO
java.util.regex.Matcher[pattern=V+N+PN+ region=0,5 lastmatch=VNPN]
NVNPN
java.util.regex.Matcher[pattern=V+N+PN+ region=0,38 lastmatch=VNNPNNN]
NNNNVPNNNNVNNPNNNVVPNNPNNVVPNVVNVVPNNO
java.util.regex.Matcher[pattern=V+N+PN+ region=0,36 lastmatch=VNPNN]
SNVNPNNVNNNONVNNVVVPNNVVVVPNNPNNNNNN
java.util.regex.Matcher[pattern=V+N+PN+ region=0,9 lastmatch=VVVNPN]
NNVVVNPNO

实际上,我想要的是输出只会显示该行一次,即使每行有不止一个与模式匹配。

4

1 回答 1

3

如果您只想打印一次匹配的行,只需使用if而不是while

if (matcher.find())
    System.out.println(line);

AMatcher不需要遍历整个输入。

于 2013-06-19T08:12:31.047 回答