iOS provides a NSRegularExpression
class for working with regular expressions. Here's how to run a regex against a string and iterate through the matches:
NSError* error;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"XXX" options:NSRegularExpressionCaseInsensitive error:&error];
NSString* string = @"HelloXXXworldXXXXXX";
__block NSUInteger count = 0;
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult* match, NSMatchingFlags flags, BOOL* stop) {
NSRange matchRange = [match range];
NSRange range = [match rangeAtIndex:0];
NSLog(@"range (%@, %@)", @(range.location), @(range.length));
NSLog(@"string: %@", [string substringWithRange:range]);
}];
What's also interesting is iOS provides NSDataDetector
, as a subclass of NSRegularExpression
.
NSError* error;
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber error:&error];
NSString* string = @"My homepage is at https://hboon.com and my phone number is 391-165-8164";
__block NSUInteger count = 0;
[detector enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult* match, NSMatchingFlags flags, BOOL* stop){
NSRange matchRange = [match range];
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL* url = [match URL];
NSLog(@"matched URL: %@", url);
} else if ([match resultType] == NSTextCheckingTypePhoneNumber) {
NSString* phoneNumber = [match phoneNumber];
NSLog(@"matched phone number: %@", phoneNumber);
}
}];
NSDataDetector
comes with pre-built matching capability for dates, addresses, links, and phone numbers, so you don't have to build your own regex for them.
PS: If you want to build more complicated regular expressions, check out my app Regex for OS X that includes tools to help build and test regular expressions.
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.