14

有没有办法在java中打印出正则表达式模式的前瞻部分?

    String test = "hello world this is example";
    Pattern p = Pattern.compile("\\w+\\s(?=\\w+)");
    Matcher m = p.matcher(test);
    while(m.find())
        System.out.println(m.group());

这个片段打印出来:

你好
世界


我想要做的是成对打印单词:

你好世界
世界这

例子

我怎样才能做到这一点?

4

1 回答 1

15

您可以简单地将捕获括号放在前瞻表达式中:

String test = "hello world this is example";
Pattern p = Pattern.compile("\\w+\\s(?=(\\w+))");
Matcher m = p.matcher(test);
while(m.find()) 
    System.out.println(m.group() + m.group(1));
于 2011-04-02T14:17:08.110 回答