The Dopefly Tech Blog

« The Dopefly Tech Blog Main page

Use regular expressions to be clever in your IDE

posted under category: General on December 6, 2007 at 1:00 am by Nathan

Here's something I do almost daily it seems. So much so that I take it for granted. A couple months ago a friend was looking over my shoulder and he exclaimed "What the--? You've got to save that and send it to me!" I explained how it was just throw-away code, and I could send it to him if he wanted. The code is long gone but that reaction stuck in my mind, so let's dive in with an example.

You have a list of values on lines and you want to want to apply some code to each:
first_name
middle_initial
last_name
phone
country
state_province
city


Select the lines, and use your IDE's find/replace tool with the regex option. In Eclipse, this is just CTRL+F and check the checkbox. Use this as the search pattern:
^(.+)$

This regex says to select any line with at least one character in it and store it in a character group.

Some code like this would be the replace pattern:
querySetCell(myQuery, "$1", "");

Replace them all and your code will be generated in an instant. The regex will drop each line's content into the $1 backreference.

There are dozens of other types of uses just like this one.