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.
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 ?
.
I think by default, quantifiers are greedy and from left to right. So its not really a greedy issue you were having its the a{0,m} in the alternation matching in the presence of non a
's. It would have matched up to 'm' a's had they been present first.
Greediness seem's more complicated than someone might guess.
'aaaaaaaaaa' =~ /(a{1,2}) (a{1,2}?) (a{1,4}) (a{4,12}+)/x
&&
print "'$1', '$2', '$3', '$4'
";
'aa', 'a', 'aaa', 'aaaa'
精彩评论