
Jasmine
Administrator
/ Moderator
Feb 7, 2000, 12:06 PM
Post #2 of 3
(303 views)
|
Straight out of the faq... You have to keep track of N yourself. For example, let's say you want to change the fifth occurrence of "whoever" or "whomever" into "whosoever" or "whomsoever", case insensitively. <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $count = 0; s{((whom?)ever)}{ ++$count == 5 # is it the 5th? ? "${2}soever" # yes, swap : $1 # renege and leave it there }igex; </pre><HR></BLOCKQUOTE> In the more general case, you can use the /g modifier in a while loop, keeping count of matches. <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $WANT = 3; $count = 0; while (/(\w+)\s+fish\b/gi) { if (++$count == $WANT) { print "The third fish is a $1 one.\n"; # Warning: don't `last' out of this loop } } </pre><HR></BLOCKQUOTE> That prints out: "The third fish is a red one." You can also use a repetition count and repeated pattern like this: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i; </pre><HR></BLOCKQUOTE> To adapt the above to your needs, you can alter the above to something like this: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $WANT = 3; $count = 0; while (/(\w+)\s+fish\b/gi) { if (++$count == $WANT) { $result = (split(/$1/,$_))[1]; # Warning: don't `last' out of this loop } } </pre><HR></BLOCKQUOTE> I haven't tested it, but you get the idea Good luck! [This message has been edited by Jasmine (edited 02-07-2000).]
|