Search code examples
regexgreedyregex-greedyquantifiers

alternative greedy match


I want to make a greedy match to an alternative of either zero to 'm' consecutive occurences of 'a' or zero to 'n' consecutive occurences of 'b'. If I do

/a{,m}|b{,n}/

it will not work because when I have sequences of 'b', it will match with 'a{,m}', and the alternative 'b{,n}' will not be looked at, and it will not be a greedy match.


Solution

  • If I understand what you're trying to do correctly, how about /(?:a{1,m}|b{1,n})?/

    It'll match either a string of consecutive a's (up to m times), or a string of consecutive b's (up to n times), or nothing at all due to the optional ?.