Thursday, July 15, 2010

Crazy Visual Studio regex

I'm not sure why, but I've never really looked into regex in the find (& replace) dialog in Visual Studio. A couple days ago I had an interesting reason to dig in, so here's my attempt to be able to do this the next time I need to.

First here are the docs on the syntax (of course I looked for this after I finished my task, so below may not be the best example): http://msdn.microsoft.com/en-us/library/aa293063(VS.71).aspx

Here are the two expressions I ended up with (I'm sure they could be better):

Find: ^{:b*}proxy\::b*new Ext.data.AspNetAjaxHttpProxy.*\n[^'"]*['"]{[^'"]*}['"]\n[^,]*
  1. A line that starts with some white space captured
  2. then "proxy:"
  3. then some white space
  4. then "new Ext.data.AspNetAjaxHttpProxy"
  5. then any characters to the end of the line
  6. then new line
  7. then any characters except a single or double quote
  8. then a single or double quote
  9. then capture the characters inside of the quotes
  10. then a new line
  11. then any characters that are not a comma
Replace: \1proxy\: window.getProxy('\2')
  1. fill in with the whitespace captured in step 1 above
  2. then insert "proxy: window.getProxy(
  3. then the chars capterd in step 9 above
  4. then insert )

Find: ^{:b*}reader\::b*new Ext.data.JsonReader\(.*\n.*\n[^,]*,:b*
Replace: \1reader\: window.getJSONReader(

Some of the things I learned:
  1. There is multi-line support, but it's not great
  2. I would have been better off using :q for my quoted string in the first example
  3. You can do grouping with "()" to capture n number of \n characters. I didn't know about this at the time, but could have used it where I have back to back ".*\n" sequences.
  4. Capture groups are pretty easy using "{}" and replacing with "\n" where 'n' is the 1 based index of the capture.

0 comments:

Post a Comment