Saturday, August 21, 2010

Searching text in a string using AS3: Way 2

In this tutorial we will learn the other way of finding a substring in a string.

The method search() is pretty easy to use. You simply specify what substring are you looking for and you get the starting index of your substring. Example:

var str:String = "The better I know him, the more I like him.";
trace(str.search("the"));

Output: 23

As you can see, this method is also case sensitive. But no worries, because search() method works with regular expressions. Let's apply a pattern of "the" with an "i" flag, which ignores case-sensitivity.

var str:String = "The better I know him, the more I like him.";
var pattern:RegExp = /the/i
trace(str.search(pattern));

Output: 0

The search() method only finds one match, even if the regular expression has a "g" tag (global). The match() method works the same, however if there's a "g" flag included in the regexp, match() returns an array of results.

var str:String = "The better I know him, the more I like him.";
var pattern:RegExp = /the/ig
trace(str.match(pattern));

Output: The, the

We can use more complex expressions, for example, a e-mail adress pattern:

var str:String = "If you need more help, contact us at help@bigdomain.com or admin@bigdomain.org or info@bigdomain.net";
var pattern:RegExp = /([a-z0-9_]+@[a-z0-9][a-z0-9-]+[a-z0-9]\.[a-zA-Z]{2,6})/ig
trace(str.match(pattern));

Output: help@bigdomain.com,admin@bigdomain.org,info@bigdomain.net

Or you could return names of people:

var str:String = "I told James to tell Richard, Harry's brother, to go to Nick's party.";
var pattern:RegExp = /[A-Z][a-z]+/g
trace(str.match(pattern));

Output: James,Richard,Harry,Nick

The possibilities are endless, use what suits you the best!

Thanks for reading.

Related:

Searching text in a string using AS3: Way 1

2 comments:

Anonymous said...

Great post man...was helpful for me!!Thanks

mikelly said...

BRILLIANT!!! I had to trace instances (from a movie playing skin's fast forward slider) which change their numbers with every instantiation (of course) so I had to single out the word "instance."
Your method worked perfectly: var pattern:RegExp = /instance/g;
e.target.name.toString().match(pattern) != "instance"
THANKS for this POST!!!!!

Post a Comment