Search code examples
regexnon-greedy

Making range of characters not greedy in Regex


I have a list of messages where I'm searching in that message for 4 or 3 digit number, I then replace it with that number.

So my current Regex is

Find

(.*)([0-9]{3,4})(.*)\r

Replace

\2

However, the problem is with [0-9]{3,4} only takes the first 3 digit if there are 4 digits, so even if there is a 4 digit number sequence, it will just grab a 3 digit number. Which is what I don't want.

Is there a way to make it grab a 4 digit number if it can and only grab a 3 digit number if it can't find the 4 digit number in that line.

Thanks


Solution

  • Regular expressions have support for non-greedyness using the *? operator:

    (.*?)([0-9]{3,4})(.*)\r
    

    Depending on the program you use to match the regex, you will need to add additional flags.

    In such case a regex is more happy to give a digit to the second group than to the first. By default regexes are greedy left-to-right: they will try to store everything in the first group and only move to the next if necessary (to still match the string).