As of iOS 4.0 and OSX 10.7, Apple provides a class NSRegularExpression
which
implements the use of regular expressions in Objective C.
An immutable instance of NSRegularExpression
is created
with a regex pattern and options, and upon execution, can create
NSTextCheckingResult
for each match.
NSTextCheckingResult
uses NSRange objects to describe the location of match
groups within the source string - so that by applying the range to the source
string, you can extract the resulting matched text.
Code
The following code demonstrates a regex in action. The search expression matches words starting with a vowel, and ending in 'd' or 's'. It will print the total number of matches, and then each group of each match. Output is below.
Output
RegexTest[23743:403] Number of Matches: 4
RegexTest[23743:403] -----
RegexTest[23743:403] Ranges: 3
RegexTest[23743:403] Match: used
RegexTest[23743:403] Range 0: used
RegexTest[23743:403] Range 1: u
RegexTest[23743:403] Range 2: d
RegexTest[23743:403] Ranges: 3
RegexTest[23743:403] Match: and
RegexTest[23743:403] Range 0: and
RegexTest[23743:403] Range 1: a
RegexTest[23743:403] Range 2: d
RegexTest[23743:403] Ranges: 3
RegexTest[23743:403] Match: expressions
RegexTest[23743:403] Range 0: expressions
RegexTest[23743:403] Range 1: e
RegexTest[23743:403] Range 2: s
RegexTest[23743:403] Ranges: 3
RegexTest[23743:403] Match: and
RegexTest[23743:403] Range 0: and
RegexTest[23743:403] Range 1: a
RegexTest[23743:403] Range 2: d