Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 956
Joshua Avatar asked Dec 04 '10 13:12

Joshua


People also ask

Which string methods are used with regular expression?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() .

How do you search a string for a pattern in JavaScript?

Using test() The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result.


2 Answers

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 }]; 
like image 173
Pablo Santa Cruz Avatar answered Sep 20 '22 01:09

Pablo Santa Cruz


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

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"); 

In Swift you may write code like this ...

Swift 2

    let string = "Telecommunication"      if string.rangeOfString("cOMm", options: (NSStringCompareOptions.RegularExpressionSearch | NSStringCompareOptions.CaseInsensitiveSearch)) != nil {         print("Got it")     } else {         print("No luck")     } 

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 2's rangeOfString(_:,options:) and Swift 4's range(of:options:) return Range<String.Index>? that returns nil if search failed

like image 25
vedrano Avatar answered Sep 21 '22 01:09

vedrano