Parker Smith Software

 

Regex find and replace

By Brian Webb

26 Oct 2010

I was recently working on an Adobe AIR project (using AS3 programming language & Flash Builder aka Eclipse as the editor) and I needed to do a major re-factor of some code in a lot of different places.  I decided to do a regular expression find and replace.  After doing some experimentation on Rublar (with Ruby code) I was able to hone my regex to match correctly, but I found a few variations with how different programs do regex find and replace.  Here's the info:



1) This is our test string:


MyStaticClass.randomMethod().someFunction( BlahClass.MY_CONSTANT ).addEventListener

which we want to find and replace to be this:


(MyStaticClass.randomMethod().someFunction(BlahClass.MY_CONSTANT) as MyNewClass).genericObject.addEventListener

2) This is the full regex notation (which I was test matching in ruby): 


/^MyStaticClass\.randomMethod\(\)\.someFunction\((.+)\).addEventListener$/x


With this regex there is 1 match capture:  BlahClass.MY_CONSTANT.  You can use the various captures in a replacement string by providing the replacement string but inserting $X where you want the capture inserted, and where "X" is the capture instance, so in this case it is $1.

I was able to do a regex find and replace in TextMate like this:

Find:


^MyStaticClass\.randomMethod\(\)\.someFunction\((.+)\).addEventListener$


Replace:


(MyStaticClass.randomMethod().someFunction($1) as MyNewClass).genericObject.addEventListener

However no such luck in Flash Builder.  After some messing around I found out that Eclipse doesn't want the beginning and end line notations, so THIS works in Eclipse:

Find: 


MyStaticClass\.randomMethod\(\)\.someFunction\((.+)\).addEventListener

Replace:


(MyStaticClass.randomMethod().someFunction($1) as MyNewClass).genericObject.addEventListener
 
 
 
No Spam: 8 + 7 =
 
October 26, 2010 - Brian Webb
0
 
October 06, 2010 - Brian Webb
1