For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > October 2006 > Re: loop over a string to do search/replacement using regexp?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: loop over a string to do search/replacement using regexp?
nobull67@gmail.com

2006-10-31, 3:57 am



On Oct 30, 10:55 pm, "Rick" <rick.peng...@gmail.com> wrote:
> Hi, guys
>
> I need to loop over a string to find some pattern A, do some
> computation according to A and replace A with B. I am trying to do this
> within a while loop but I have no idea how to plug s///g into this
> loop. Can anyone offer some clue?


Clue: s///g _is_ a looping constuct.

> Here is an example: In string 'a123ba456b', the pattern to find is
> a(.*?)b and this string needs to be processed as 'a(1)ba(2)b', meaning
> that the occurance of '123' is recorded and put back into the original
> string.


I don't know what you mean by that.

If you want to save the matching patterns to an array and put an index
in parentheses in place of the saved string.

s/(a)(.*?)(b)/$1(@{ push @save, $2; [ scalar @save ]})$3/g;

OR

s/(a)(.*?)(b)/ push @save, $2; "$1(" . @save . ")$3" /eg;

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com