Wednesday, December 29, 2004

Regular Expressions

I regularly use JEdit (a Java-based code editor by Slava Pestov and company) and occassionally need to use a regular expression when doing a find/replace. Most of the time my regular expressions are simple and just look for a new line character (e.g., ">\n") but today I had something a bit more interesting.

I wanted to append a string to every line of a properties file that wasn't a comment line or a blank line and didn't contain a path. So the find expression looked something like "(^[^#^\n][^\\^\n]+$)". The interesting part was the replace expression which looked like "$0 suffix". The $0 says take the contents of the group (the stuff between the parentheses found by the first regex) and append the word "suffix". Very cool.

#this is a test

abc=c:\abc\def
def=test
ghi=this is a message

#another comment
jkl=Define:

turned into something like this:

#this is a test

abc=c:\abc\def
def=test suffix
ghi=this is a message suffix

#another comment
jkl=Define: suffix

No comments: