javaworld
javaworld

Reputation: 435

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

Upvotes: 0

Views: 83

Answers (1)

ajb
ajb

Reputation: 31689

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().

Upvotes: 2

Related Questions