Joshua
Joshua

Reputation: 15510

Search through NSString using Regular Expression

How might I go about searching/enumerating through an NSString using a regular expression?

A regular expression such as: /(NS|UI)+(\w+)/g.

Upvotes: 41

Views: 45410

Answers (2)

vedrano
vedrano

Reputation: 2971

If you just want to match some pattern in string, there is a simple way to test Regular Expression with NSString:

ObjC

rangeOfString:options:

NSString *string = @"Telecommunication";

if ([string rangeOfString:@"comm" options:NSRegularExpressionSearch].location != NSNotFound)

    NSLog(@"Got it");

else

    NSLog(@"No luck");

Note, often you'll want ...

if ([string rangeOfString:@"cOMm"
  options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location
  != NSNotFound)
     NSLog(@"yes match");

Swift 4

let string = "Telecommunication"

if string.range(of: "cOMm", options: [.regularExpression, caseInsensitive]) != nil {
    print("Got it")
} else {
    print("No luck")
}

Please take note that Swift's range(of:options:) returns Range<String.Index>? that returns nil if search failed.

(in Swift 2, the name was rangeOfString(_:options:))

Upvotes: 37

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

You need to use NSRegularExpression class.

Example inspired in the documentation:

NSString *yourString = @"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"(NS|UI)+(\\w+)"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    // your code to handle matches here
}];

Upvotes: 60

Related Questions