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";