macOS NSRegularExpression
│ English (en) │
This article applies to macOS only.
See also: Multiplatform Programming Guide
Regular expressions
Regular expressions are patterns used to match specified alpha-numeric character combinations in the string data being searched.
Each character in a regular expression (that is, each character in the string describing its pattern) is either a metacharacter, having a special meaning, or a regular character that has a literal meaning.
NSRegularExpression Overview
The NSRegularExpression class has convenience methods for returning all the matches as an array, the total number of matches, the first match, and the range of the first match.
An individual match is represented by an instance of the NSTextCheckingResult class, which carries information about the overall matched range (via its range property), and the range of each individual capture group (via the range_AtIndex method).
NSRegularExpression conforms to the International Components for Unicode (ICU) specification for regular expressions.
Code Example
Program regex_ex1;
{$mode objfpc}{$H+}
{$modeswitch objectivec2}
Uses
MacOSAll, CocoaAll, SysUtils;
Var
srchStr : String;
patnStr : String;
myRegex : NSregularExpression;
matches : NSArray;
match : NSTextCheckingResult;
error : NSErrorPtr;
Begin
error := Nil;
srchStr := 'I have 43 bags of 60 marbles.';
patnStr := '\d+';
myRegex := NSregularExpression.regularExpressionWithPattern_options_error(NSStr(patnStr), NSRegularExpressionOptions(NSRegularExpressionCaseInsensitive), error);
if(error <> Nil) then
NSLog(NSStr('Error: %@'), error);
matches := myRegex.matchesInString_options_range(NSStr(srchStr), 0, NSMakeRange(0, srchStr.Length));
NSLog(NSStr('Search string: %@'), NSStr(srchStr));
NSLog(NSStr('Pattern string: %@'), NSStr(patnStr));
NSLog(NSStr('Number of matches: %lu'), myRegex.numberOfMatchesInString_options_range(NSStr(srchStr), 0, NSMakeRange(0, srchStr.Length)));
for match in matches do
NSLog(NSStr('match: %@'), NSStr(srchStr).substringWithRange(match.rangeAtIndex(0)));
End.
The output from running the above code example is:
2021-06-12 21:05:46.335 regex_ex1[26138:232243] Search string: I have 43 bags of 60 marbles. 2021-06-12 21:05:46.336 regex_ex1[26138:232243] Pattern string: \d+ 2021-06-12 21:05:46.336 regex_ex1[26138:232243] Number of matches: 2 2021-06-12 21:05:46.336 regex_ex1[26138:232243] match: 43 2021-06-12 21:05:46.336 regex_ex1[26138:232243] match: 60