User Guide

308 Using Regular Expressions
The call to the replace() method employs the regular expression and assembles the
replacement HTML string, using backreferences.
The
urlToATag() method then calls the emailToATag() method, which uses similar
techniques to replace e-mail patterns with HTML
<a> hyperlink strings. The regular
expressions used to match HTTP, FTP, and e-mail URLs in this sample file are fairly simple,
for the purposes of exemplification; there are much more complicated regular expressions for
matching such URLs more correctly.
Converting U.S. dollar strings to euro strings
When the user clicks the Test button in the sample application, if the user selected the
dollarToEuro check box, the application calls the CurrencyConverter.usdToEuro() static
method to convert U.S. dollar strings (such as
"$9.95") to euro strings (such as "8.24 €"), as
follows:
var usdPrice:RegExp = /\$([\d,]+.\d+)+/g;
return input.replace(usdPrice, usdStrToEuroStr);
The first line defines a simple pattern for matching U.S. dollar strings. Notice that the $
character is preceded with the backslash (
\) escape character.
The
replace() method uses the regular expression as the pattern matcher, and it calls the
usdStrToEuroStr() function to determine the replacement string (a value in euros).
When a function name is used as the second parameter of the
replace() method, the
following are passed as parameters to the called function:
The matching portion of the string.
Any captured parenthetical group matches. The number of arguments passed this way
varies depending on the number of captured parenthetical group matches. You can
determine the number of captured parenthetical group matches by checking
arguments.length - 3 within the function code.
The index position in the string where the match begins.
The complete string.
The
usdStrToEuroStr() method converts U.S. dollar string patterns to euro strings, as
follows:
private function usdToEuro(...args):String
{
var usd:String = args[1];
usd = usd.replace(",", "");
var exchangeRate:Number = 0.828017;
var euro:Number = Number(usd) * exchangeRate;
trace(usd, Number(usd), euro);