Java中的非贪婪正则表达式 [英] Non-greedy Regular Expression in Java

查看:365
本文介绍了Java中的非贪婪正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码:

public static void createTokens(){
    String test = "test is a word word word word big small";
    Matcher mtch = Pattern.compile("test is a (\\s*.+?\\s*) word (\\s*.+?\\s*)").matcher(test);
    while (mtch.find()){
        for (int i = 1; i <= mtch.groupCount(); i++){
            System.out.println(mtch.group(i));
        }
    }
}

并具有下一个输出:

word
w

但是我认为它必须是:

word
word

请有人向我解释为什么?

Somebody please explain me why so?

推荐答案

由于您的模式不贪心,因此它们在仍由匹配项组成的情况下,尽可能少地匹配文本.

Because your patterns are non-greedy, so they matched as little text as possible while still consisting of a match.

删除?在第二组中,您会得到

词词大小

Remove the ? in the second group, and you'll get
word
word word big small

Matcher mtch = Pattern.compile("test is a (\\s*.+?\\s*) word (\\s*.+\\s*)").matcher(test);

这篇关于Java中的非贪婪正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆