regexregex-greedynon-greedy

Regular Expression nongreedy is greedy


I have the following text

tooooooooooooon

According to this book I'm reading, when the ? follows after any quantifier, it becomes non greedy.

My regex to*?n is still returning tooooooooooooon.

It should return ton shouldn't it?

Any idea why?


Solution

  • A regular expression can only match a fragment of text that actually exists.

    Because the substring 'ton' doesn't exist anywhere in your string, it can't be the result of a match. A match will only return a substring of the original string

    EDIT: To be clear, if you were using the string below, with an extra 'n'

    toooooooonoooooon
    

    this regular expression (which doesn't specify 'o's)

    t.*n
    

    would match the following (as many characters as possible before an 'n')

    toooooooonoooooon
    

    but the regular expression

    t.*?n
    

    would only match the following (as few characters as possible before an 'n')

    toooooooon