41

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

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

Demitri
  • 13,134
  • 4
  • 40
  • 41
Joshua
  • 15,200
  • 21
  • 100
  • 172

2 Answers2

60

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
}];
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 2
    This is the code I am using including the string, https://gist.github.com/728216. However it doesn't work and the `NSLog`'s are not called. – Joshua Dec 04 '10 at 14:31
  • I have checked that `(NS|UI)+(\w+)` is a valid regular expression on http://www.regextester.com/. – Joshua Dec 04 '10 at 15:07
  • 1
    You need to double-escape those backslashes. – d11wtq Dec 05 '10 at 00:10
  • You mean `\w`? That is a meta character which will match a word character. – Joshua Dec 05 '10 at 07:54
  • 13
    Joshua - `\w` is indeed the correct meta character, but the backslash character is used in normal strings as an escape character. The compiler's string parser will change `\w` to simply `w` before it is ever passed to the RegEx object. Run an NSLog to see for yourself. The correct notation is therefore `\\w`, as the compiler will convert '\\' to '\'. This convention is present in many languages. – Endemic Dec 06 '10 at 16:11
  • Would someone mind to edit the answer and set `\\w` (instead of `\w`), I'm no Obj-C expert (yet) so I won't do it - but it is misleading to let a wrong answer as *accepted* for so long, if the backslash truly deserves to be doubled. – Déjà vu Apr 12 '12 at 08:15
37

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

Ky -
  • 30,724
  • 51
  • 192
  • 308
vedrano
  • 2,961
  • 1
  • 28
  • 25
  • `NSRegularExpressionSearch` isn't among the documented options, are you sure it's ok to do this? – Iulian Onofrei Jul 02 '15 at 08:15
  • Actually, you still can use this code snippet in Objective-C code but in Swift it should be NSStringCompareOptions.RegularExpressionSearch – vedrano Jul 02 '15 at 08:49