带有前瞻的 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
Java regular expression with lookahead
提问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));