带有前瞻的 Java 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5523654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:31:55  来源:igfitidea点击:

Java regular expression with lookahead

javaregexpattern-matchingregex-lookarounds

提问by aykut

is there a way to print out lookahead portion of a regex pattern in java?

有没有办法在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?

我怎样才能做到这一点?

采纳答案by Tim Pietzcker

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