Sunday, July 10, 2011

ActionScript Regular Expression Tester/Visualizer

Here is an improved version of my older post. Given that I already had the index of each occurrence in my hand, why not visualize it ? I chose the RichText spark component to show the matches.

I wanted to make the font style to bold and change the color to red of each match. I first thought of looping through each occurrence and concatenating to produce the RichText. But it wasn't necessary at all. The replace function of string took in a RegEx and all was easy. The replace function not only took in RegEx but also had the functionality to include the matching string in the replacement string as a parameter. That's right! The parameter is $&. See the code below. Oh and I had to handle the new lines too.

var expression:RegExp = new RegExp(txtRegularExpression.text, "g");                        
var newLineExpression:RegExp = new RegExp("\\n", "g");
var stringToShow:String = txtStringToMatch.text.replace(newLineExpression, "<br/>");
stringToShow = stringToShow.replace(expression, "<b><font size='12' color='#FF0000'>$&</font></b>");
richText.textFlow = TextConverter.importToFlow(stringToShow, TextConverter.TEXT_FIELD_HTML_FORMAT);

Saturday, July 9, 2011

ActionScript Regular Expression Tester

Here is a little tool I created using Adobe Flex to match a string against a regular expression. It tries to mimic the functionality of matches() function in .NET Regular Expression to return an array of matches. I have another idea to improve this, so I am back to work!

Here is matches function that I used. The application is after the code.

public static function getMatches(expression:RegExp, stringToMatch:String):Array
            if (!
                throw new Error(" is not true!");
            var matches:Array = new Array();
            var allMatchesFound:Boolean = false;
            while (allMatchesFound == false)
                var match:String = expression.exec(stringToMatch);
                if(match != null)
                    allMatchesFound = true;
            return matches;