sawa
sawa

Reputation: 168259

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.

Upvotes: 1

Views: 647

Answers (2)

user557597
user557597

Reputation:

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'

Upvotes: 0

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94284

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 ?.

Upvotes: 1

Related Questions