简体   繁体   English

java正则表达式lookahead非捕获但输出它

[英]java regular expression lookahead non-capture but output it

i am trying to use the pattern \\w(?=\\w) to find 2 consecutive characters using the following, although lookahead works, i want to output the actual matched but not consume it 我正在尝试使用模式\\ w(?= \\ w)使用以下内容找到2个连续的字符,虽然lookahead工作,我想输出实际匹配但不消耗它

here is the code: 这是代码:

Pattern pattern = Pattern.compile("\\w(?=\\w)");
Matcher matcher = pattern.matcher("abcde");

while (matcher.find())
{
    System.out.println(matcher.group(0));
}

i want the matching output: ab bc cd de 我想要匹配的输出: ab bc cd de

but i can only get abcde 但我只能得到abcde

any idea? 任何的想法?

The content of the lookahead has zero width, so it is not part of group zero. 前瞻的内容具有零宽度,因此它不是组零的一部分。 To do what you want, you need to explicitly capture the content of the lookahead, and then reconstruct the combined text+lookahead, like this: 要执行您想要的操作,您需要明确捕获前瞻的内容,然后重新构建组合文本+前瞻,如下所示:

Pattern pattern = Pattern.compile("\\w(?=(\\w))");
//                                       ^   ^
//                                       |   |
//                             Add a capturing group

Matcher matcher = pattern.matcher("abcde");

while (matcher.find()) {
    // Use the captured content of the lookahead below:
    System.out.println(matcher.group(0) + matcher.group(1));
}

Demo on ideone. 在ideone上演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM