Hi all,

I'm running into a problem I don't understand. I have a bunch of variables named of the form [lower case letter][one or two digit number][capital letter][# of lower case letters], and i'm trying to extract everything before the capital letter and rename the variable. I've tried using regexs and regexm to loop over the variable names and rename them but the function always defaults to the last variable in the local varlist.

The function works well on it's own though. E.g.

Code:
clear all
set obs 15
gen id = _n
gen test = "b1Kasjdad"
replace test = "b12Flkskdj" if _n>3
replace test = "c14Hdasliv" if _n>6
replace test = "d9Lpoawfe" if _n>9
replace test = "h99Mnqwdi" if _n>12
gen test2 = regexs(0) if regexm(test, "[a-z][0-9]*")
generates this dataset

Code:
clear
input float id str10 test str3 test2
 1 "b1Kasjdad"  "b1" 
 2 "b1Kasjdad"  "b1" 
 3 "b1Kasjdad"  "b1" 
 4 "b12Flkskdj" "b12"
 5 "b12Flkskdj" "b12"
 6 "b12Flkskdj" "b12"
 7 "c14Hdasliv" "c14"
 8 "c14Hdasliv" "c14"
 9 "c14Hdasliv" "c14"
10 "d9Lpoawfe"  "d9" 
11 "d9Lpoawfe"  "d9" 
12 "d9Lpoawfe"  "d9" 
13 "h99Mnqwdi"  "h99"
14 "h99Mnqwdi"  "h99"
15 "h99Mnqwdi"  "h99"
end
The variable test2 is exactly how I want to name my variable names. My dataset is currently more in the format like this

Code:
clear
input float(id b1Kasjdad b12Flkskdj c14Hdasliv d9Lpoawfe h99Mnqwdi)
 1 .36276805   .6640378  .2363827 .35137045    .431756
 2 .31382445 .036803816  .6764786  .6978495   .7970607
 3  .6380712   .3336498 .14591032  .7828125   .5824112
 4 .18699375   .7824295 .29664016  .8312564   .1161198
 5 .50534767  .01700492  .8219558  .8498105    .742251
 6  .5276305   .2278204  .3213928  .9997507  .26177752
 7  .7853414  .57824653  .4164997 .09139451   .8069862
 8  .4717338   .7533595 .02369639  .6306959    .667398
 9  .2299842   .8570072  .3125404 .07612886   .2427153
10  .7976828   .9322746  .9322619  .3457762    .629151
11 .16493952    .324447  .0502046 .09631826  .53290236
12   .932945   .1637711  .6221892 .54500425   .7275901
13  .3999315    .958201  .6189114  .8078102   .6358732
14  .9881987   .6008608  .9028944  .1186969  .30897725
15  .9287856   .9733476  .3830579  .2723139 .031594325
end
If I then run

Code:
foreach var of varlist b1Kasjdad - h99Mnqwdi{
    rename `var' `=regexs(0) if regexm("`var'", "[a-z][0-9]*")'
}
It names the first variable in varlist h99 and then tries to do the same for the second variable in varlist but, naturally, returns an error because that variable name is already in use.

Any thoughts on what i'm doing wrong here?

Thanks!