The Dopefly Tech Blog

« The Dopefly Tech Blog Main page

Using regex in your IDE #2

posted under category: General on December 7, 2007 by Nathan

We had some good responses to yesterday's post, Use regular expressions to be clever in your IDE, so today I'll post another example. This time, it's the exact opposite.

Yesterday, we created code that will end up like this:

querySetCell(myQuery, "first_name", "Nathan");
querySetCell(myQuery, "middle_initial", "J");
querySetCell(myQuery, "last_name", "Strutz");
querySetCell(myQuery, "phone", "480-123-4567");
querySetCell(myQuery, "country", "US");
querySetCell(myQuery, "state_province", "AZ");
querySetCell(myQuery, "city", "Phoenix");


Now, what do you do when you want to get just the column names out of that mess? For me, I would use this search pattern:
querySetCell\(\w+, "([^"]+)",.+

The regex says to find the word "querySetCell", any query name - the actual word myQuery could be put here -, a quote, then save any character that's not a quote up to the next quote, a comma, and then anything until the end of the string (in our case, the line).

With regular expressions and code, always remember to escape special characters in your code, such as parentheses, square brackets, backslashes and so on.

Replace it with this matched text:
$1
Or be creative :)

There you have it, right back to the original list we started with yesterday.


Another thing to remember is that it's the parentheses that define the backreferences ($1 because we have just one). Nothing's stopping you from capturing the content in the column value portion of the querySetCell calls. Something like this would allow you to use that as $2:
querySetCell\(\w+, "([^"]+)", "?([^"\)]+)"?.*

Then replace it with:
myStruct.$1 = "$2";

Nathan is a software developer at The Boeing Company in Charleston, SC. He is essentially a big programming nerd. Really, you could say that makes him a nerd among nerds. Aside from making software for the web, he plays with tech toys and likes to think about programming's big picture while speaking at conferences and generally impressing people with massive nerdiness and straight-faced sarcastic humor. Nathan got his programming start writing batch files in DOS. It should go without saying, but these thought and opinions have nothing to do with Boeing in any way.
This blog is also available as an RSS 2.0 feed. Click your heels together and click here to contact Nathan.