
japhy
Enthusiast
/ Moderator
Aug 12, 2000, 9:27 PM
Post #2 of 3
(1542 views)
|
|
Re: Substitution not working in RegExp
[In reply to]
|
Can't Post
|
|
Your problem is that the substitution starts where it left off. <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str = "abXXXc"; $str =~ s/bX/b/g; # $str is now "abXXc" </pre><HR></BLOCKQUOTE> This code doesn't remove all the X's after the b, only the first one: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> # the [] means "the regex starts looking here" string: [a]bXXXc regex: s/bX/b/ match: abXXXc # changes 'bX' to 'b' string: ab[X]Xc regex: s/bX/b/ no match </pre><HR></BLOCKQUOTE> You would want something like: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> 1 while $str =~ s/bX/b/; </pre><HR></BLOCKQUOTE> But this can be optimized, since we can just say: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str =~ s/bX+/b/; # change a 'b' followed by 1 or more X's to 'b' </pre><HR></BLOCKQUOTE> We could tack on a /g modifier if there'd be more than one set of bXXX... in the string. We can be even neater, and use a positive look-behind assertion: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $str =~ s/(?<=b)X+//; # change 1 or more X's to "" IF the first X is preceeded by a b </pre><HR></BLOCKQUOTE> Modify/alter to fit your code accordingly. ------------------ Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher [This message has been edited by japhy (edited 08-12-2000).]
|