Re: all matches of a regex

From: Jan Eden (lists_at_jan-eden.de)
Date: 02/15/04


Date: Sun, 15 Feb 2004 13:19:58 +0100
To: Qznur__Ta=FEtan?= <oznurtastan@su.sabanciuniv.edu>,   Perl Lists <beginners@perl.org>


Íznur Ta■tan wrote:

>Hi,
>I have been trying to solve a problem which is about to drive me crazy.
>May be some one know the answer(hopefully:)
>
>I want to get all macthes of a pattern in a string including the overlaping
>ones.
>For example
>the string is "xHxxHyyKzDt"
>and the pattern is /^(.*)H(.*)K(.*)D(.*)$/
>
>so in one round of match $1=x $2=xxHyy $3=z $4=t
>in another $1=xHxx $2=yy $3=x $4=t
>
I am not sure what concept your are referring to by "round", but you will never get the first result in any "round": Your quantifiers are greedy, so the first pair of brackets will always try to match as many characters as possible, as long as they are followed by H. So $1 will always be "xHxx", given your example string, $2 will be "yy" etc.

Your pattern assumes three capital letters in a string as a kind of delimiter and will not be able to use more than one "H" as the first delimiter.

If the only difference is more than one "H" delimiter in all of your strings, you could try to run two different pattern, the second one using a non-greedy quantifier for your first grouping parentheses:

/^(.*?)H(.*)K(.*)D(.*)$/

Could you explain a little more detailed what your are trying to achieve? Maybe there's another way to do it.

HTH,

Jan

-- 
There are 10 kinds of people:  those who understand binary, and those who don't