使用Pattern和Matcher时显示行

时间:2013-06-19 08:06:28

标签: java regex

当在一行中有两个或更多字符与模式匹配时,我们只能打印一次这样的行吗?

例如:

    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

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

1 个答案:

答案 0 :(得分:3)

如果您只打印一次匹配的行,请使用if代替while

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

Matcher需要来完成整个输入。

相关问题