Using Visual Studio Find and Replace for language transformations
Innsendt: 09.12.10 Arkivert i: code Leave a comment »Sometimes I need to create code from data, normally to create scripts for deployment to multiple environments. Since this often is a one time job, it makes no sense to make or buy a tool for doing this.
Being a former Perl-programmer, I have a powerful tool in my toolbelt: regex.
This is a real example from a recent project.
I had quite a few sql-statements like this:
update maparea set extentx1=100616, extentx2=6654051,extenty1=139033,extenty2=6700901 where id = 110;
I wanted to create migration code for FluentMigrations, which should look like this:
Update.Table("maparea").Set(new {extentx1=179073, extentx2=7001157,extenty1=202727,extenty2=7012535}).Where(new {id= 390});
I pasted the sql statements into visual studio, and used Find and Replace to convert the statements.
Find what:
update {:w} set {.+} where {:w= :z}.+
Replace with:
Update.Table("\1").Set(new {\2}).Where(new {\3});
The trick is using {groups}to match the part of the expression I want to reuse in my new code, and group references, \1, \2 etc., to insert it in the right place.
After that I just press Replace All : )