【问题标题】:java regular expression lookahead non-capture but output itjava正则表达式前瞻非捕获但输出它
【发布时间】:2014-07-24 20:35:05
【问题描述】:

我正在尝试使用模式 \w(?=\w) 使用以下内容查找 2 个连续字符, 虽然前瞻有效,但我想输出实际匹配但不消耗它

代码如下:

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

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

我想要匹配的输出:ab bc cd de

但我只能得到a b c d e

有什么想法吗?

【问题讨论】:

    标签: java regex lookahead


    【解决方案1】:

    前瞻内容的宽度为零,因此它不是零组的一部分。做你想做的事,你需要显式地捕获lookahead的内容,然后重构组合的text+lookahead,像这样:

    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.

    【讨论】:

    • @DayDayHappy 这将导致不支持答案(+1 btw):D
    • 真的。下次我会按 (2n+1) 次
    猜你喜欢
    • 2011-10-25
    • 2013-12-24
    • 2017-05-07
    • 2012-06-22
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多