14

is there a way to print out lookahead portion of a regex pattern in 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());

this snippet prints out :

hello
world
this
is

what I want to do is printing the words as pairs :

hello world
world this
this is
is example

how can I do that?

tchrist
  • 78,834
  • 30
  • 123
  • 180
aykut
  • 563
  • 2
  • 6
  • 18

1 Answers1

15

You can simply put capturing parentheses inside the lookahead expression:

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));
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Nice. I was going to suggest `\w+\s(?=(\w+))\1` without changing the Java code, but this consumes the capturing group... – flow2k Mar 11 '19 at 23:57