Title here
Summary here
Regular expressions in ActionScript are handled using the RegExp
class. Here are some examples of common regexp-related tasks in ActionScript.
package {
import flash.display.Sprite;
import flash.text.TextField;
public class RegularExpressions extends Sprite {
public function RegularExpressions() {
var output:TextField = new TextField();
output.width = 400;
output.height = 400;
addChild(output);
// This tests whether a pattern matches a string.
var match:Boolean = /p([a-z]+)ch/.test("peach");
output.appendText(match.toString() + "\n");
// In ActionScript, we don't need to compile the regex separately.
// We can use it directly.
var r:RegExp = /p([a-z]+)ch/;
// Here's a match test like we saw earlier.
output.appendText(r.test("peach").toString() + "\n");
// This finds the match for the regexp.
var result:Object = r.exec("peach punch");
output.appendText(result[0] + "\n");
// The index of the match can be found in the index property.
output.appendText("idx: [" + result.index + " " + (result.index + result[0].length) + "]\n");
// The exec method returns an array with the full match and any capturing groups.
output.appendText(result.toString() + "\n");
// To find all matches, we can use a loop with the exec method.
var allMatches:Array = [];
var str:String = "peach punch pinch";
while ((result = r.exec(str)) !== null) {
allMatches.push(result[0]);
}
output.appendText(allMatches.toString() + "\n");
// To replace subsets of strings with other values:
output.appendText(("a peach").replace(r, "<fruit>") + "\n");
// To transform matched text with a function:
function toUpper(match:String, ...args):String {
return match.toUpperCase();
}
output.appendText(("a peach").replace(r, toUpper) + "\n");
}
}
}
This ActionScript code demonstrates various operations with regular expressions:
test
method.exec
method.Note that ActionScript’s regular expression handling is somewhat different from some other languages:
exec
method is used for finding matches, and it returns null
when no more matches are found.exec
.exec
and replace
.For more information on regular expressions in ActionScript, refer to the ActionScript documentation on the RegExp
class.