java regex reluctant quantifier giving greedy quantifier

im trying out java regex quantifiers

    Pattern p = Pattern.compile("^s(.*?)n$");
    Matcher m = p.matcher("sensation");
    if(m.matches()){
        System.out.println("dude how is this even possible");
        System.out.print(m.group() + m.start()+m.end()+"n");



    }else {
        System.out.println("sorry dude someting wrong");
    }

since it was relecutant quantifier it was supposed to give the following result sen sation

but instead im getting sensation where does it went wrong or what did i missed


You've told the program twice that your pattern needs to match the entire string. That's why it can't match just the "sen" part, even when you use a reluctant qualifier.

(1) The $ at the end of the pattern matches the end of the string; it will not let you match "sen" because "sen" isn't followed by the end of the string.

(2) You're using m.matches() , which only returns true if the entire string is matched. See the definition of matches .

Remove $ and change matches() to find() .

链接地址: http://www.djcxy.com/p/76934.html

上一篇: python中所有格量词的替代

下一篇: java正则表达式给予贪婪量词的勉强量词