带有lookahead的Java正则表达式

ayk*_*kut 12 java regex pattern-matching regex-lookarounds

有没有办法在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());
Run Code Online (Sandbox Code Playgroud)

这个片段打印出来:

你好
世界


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

你好世界
世界,这
本是
就是例子

我怎样才能做到这一点?

Tim*_*ker 12

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

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));
Run Code Online (Sandbox Code Playgroud)