Share/Save/Bookmark Subscribe

Friday, May 21, 2010

Some useful regular expression patterns when porting code between languages

I'm currently moving a lot of code from Java to Actionscript, and regex has been a lifesaver. Here are some of the patterns that proved invaluable, and that would work on most c-style languages. The Actionscript replacements are obviously specific to that language, but changing them for a different output language really would be trivial:

Find non-parameter variable declarations and assignments
Note: this will find returns as well, see the next pattern
(\w+)(\s)(\w+)(;|\s=)

Flash replacement:
var$2$3:$1$4

Will replace:
    int myInt;
    boolean myBool = true;
With:
    var myInt:int;
    var myBool:boolean = true;   

Find resulting returns in Flash
This will match all the wonky return statements resulting from the previous replacement.
var(\s)(\w+):return;

Flash replacement:
return$1$2;

Will replace:
    var true:return;
With:
    return true;

Find parameter variable declarations
(\w+)(\s)(\w+)(,|\))

Flash replacement:
$3:$1$4

Will replace:
    public int foo(int intParam, boolean boolParam) {
With:
    public int foo(intParam:int, boolParam:boolean) {

Find function signatures with parameters in c/java format
(\w+)(\s)(\w+\([\s?\w\s\w+,?]*\))(\s?\{)

Flash replacement:
function$2$3:$1$4

Will replace:
    public int foo(int intParam, boolean boolParam) {
With:
    public function foo(int intParam, boolean boolParam):int {


Find function signatures with parameters in Actionscript format
(\w+)(\s)(\w+\([\s?\w+:\w+,?]*\))(\s?\{)

Flash replacement:
function$2$3:$1$4

Will replace:
    public int foo(intParam:int, boolParam:int) {
With:
    public function foo(intParam:int, boolParam:int):int {

Find numeric types
(,|;|\(|\)|=|\s)(int|long|short|float|double|byte)(,|;|\(|\)|=|\s)

Flash replacement:
Number

Will replace:
    var myInt:int;
    long myLong;
    float foo(byte bar) {
With:
    var myInt:Number;
    Number myLong;
    Number foo(Number bar) {

Posted via email from Matt's thoughts

blog comments powered by Disqus
 

Copyright 2007 All Right Reserved. shine-on design by Nurudin Jauhari. and Published on Free Templates

Afrigator