开发者

Java regular expression with lookahead

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+开发者_JAVA技巧)");
    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?


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜