Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with regular expression puzzle

Status
Not open for further replies.

weloki

Technical User
Feb 19, 2004
12
US
suppose i have the string: "iX... iY... iX... iY"
and i want to replace all occurrences of iX with "i1" and all occurrences of iY with "i2", yielding "i1... i2... i1... i2"
how can i do this with a single regular expression that will also replace the string
"iY... iX... iY... iX" with the string "i1... i2... i1...i2"?
ideally, this same regex would also be able to replace the string "iX... iX... iY... iZ" with the string "i1... i1... i2... i3"
and the string "iY... iZ... iZ... iX" with the string "i1... i2... i2... i3"
etc...

i have tried:
if ($_ =~ m/i[A-Z]/)
{$_ =~ s/i([A-Z])/i$1 1/g;
$_ =~ s/i([^A-Z])/i$1 2/g;
print ("$_\n");}
else {print ("try again");}

but it would be best if instead of just replacing X, Y, or Z, that any capital letter or string of capital letters (e.g. BB, VAR, FINDME, etc.) can be replaced. i only used the specific letters X-Z as examples to try to describe the problem. As far as what i need them replaced with, it would be best if the replacements are based on the occurrence of the capital letters from left to right - the first occurrence is always replaced with "1" and any following occurrence of that same letter will be replaced with "1" since that number was associated with that letter upon the its first occurrence in the string. After that first letter, any other letter L would be replaced with "2" as well as any successive occurrence of letter L. So, for another example, the string: "iA ... iL ... iA ... iBLA ... iL ... iQA ..." would be replaced as such (read "->" as "replaced with"):
iA -> i1, iL -> i2, iBLA -> i3, iQA -> i4 ...
this is how i need the letters to be replaced, based on their respective appearances in the string. So since "A" is first it is 1 and all later "A"s are also "1", likewise, since "L" is the 2nd different letter in the string, it and all later occurrences of "L" are "2". but if: "iA ... iA ... iL" then "L" would still be labeled "2".
so the resulting string will look like this: "i1 ... i2 ... i1 ... i3 ... i2 ... i4 ... ...in
 
If your string is stored in $str, this should work (not tested throuroughly):
Code:
my %replacements;
my $counter = 0;
$str =~ s/(?<=i)([A-Z]+)/$replacements{$1} ||= ++$counter/ge;
 
thanx ishnid, i posted a reply to yours on dev shed...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top