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);

No comments:

Post a Comment