AS3: Regular Expression Basics


 / Published in: ActionScript 3
 

  1. RegExp.text(string) returns a Boolean
  2. RegExp.exec(string) returns an Object
  3. String.search(pattern) returns an int
  4. String.match(pattern) returns an Array
  5. String.replace(pattern, replace) returns a String
  1. //Using Replace
  2. var toungeTwister:String = "Peter Piper Picked a peck of pickled peppers";
  3. //g is a global identifier so it doesn't stop only on the first match
  4. var pickRegExp:RegExp = /pick|peck/g;
  5. var replaced:String = toungeTwister.replace( pickRegExp, "Match");
  6. //trace(replaced);
  7.  
  8. //Using Character Classes
  9. var compassPoints:String = "Naughty Naotersn elephants squirt water";
  10. var firstWordRegExp:RegExp = /N(a|o)/g;
  11. //trace( compassPoints.replace( firstWordRegExp, "MATCH" ) );
  12.  
  13. var favoriteFruit = "bananas";
  14. var bananaRegExp:RegExp = /b(an)+a/;
  15. //trace( bananaRegExp.test( favoriteFruit ) );
  16.  
  17. //Exec() method returns an Object containing the groups that were matched
  18. var htmlText:String = "<strong>This text is important</strong> while this text is not as important <strong>ya</strong>";
  19. var strongRegExp:RegExp = /<strong>(.*?)<\/strong>/g;
  20. var matches:Object = strongRegExp.exec( htmlText);
  21. for( var i:String in matches ) {
  22. //trace( i + ": " + matches[i] );
  23. }
  24.  
  25. var email:String = "[email protected]";
  26. var emailRegExp:RegExp = /^([a-zA-Z0-9_-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,4})$/i;
  27. var catches:Object = emailRegExp.exec( email );
  28. for( var j:String in catches ) {
  29. //trace( j + ": " + catches[j] );
  30. }
  31. //trace( "This e-mail's validity is: " + emailRegExp.test( email ) );
  32.  
  33. //Test the validity of an e-mail
  34. var validEmailRegExp:RegExp = /([a-z0-9._-]+)@([a-z0-9.-]+)\.([a-z]{2,4})/;
  35. trace( validEmailRegExp.test( "[email protected]" ) );
  36.  
  37.  
  38. //Return a Boolean if there is a pattern match
  39. var phoneNumberPattern:RegExp = /\d\d\d-\d\d\d-\d\d\d\d/;
  40. trace( phoneNumberPattern.test( "347-555-5555" )); //true
  41. trace( phoneNumberPattern.test("Call 800-123-4567 now!")); //true
  42. trace( phoneNumberPattern.test("Call now!")); //false
  43.  
  44. //Return the index number of the occurence is there is a pattern match
  45. var themTharHills:String = "hillshillshillsGOLDhills";
  46. trace(themTharHills.search(/gold/i)); //15

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: outbox on June 11, 2008

comment test

Posted By: cantaki on August 10, 2008

Great post, one error at the start: "RegExp.text(string) returns a Boolean", it should say RegExp.test instead of .text

This is a great summary though, thanks!

Posted By: stealfish on February 2, 2011

great summary!

You need to login to post a comment.