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 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.

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.