Scott Scott - 6 months ago 19
iOS Question

Detect whole word in NSStrings

How do I detect if an NSString contains a specific word, e.g.

is
.

If the NSString is
Here is my string. His isn't a mississippi isthmus. It is...
? The method should detect the word
is
and return
YES
.

However, if the NSString is
His isn't a mississipi isthmus
, it should return
NO
.

I tried using
if ([text rangeOfString:@"is" options:NSCaseInsensitiveSearch].location != NSNotFound) { ... }
but it detects characters not words.

Answer

Use "regular expression" search with the "word boundary pattern" \b:

NSString *text = @"Here is my string. His isn't a mississippi isthmus. It is...";
NSString *pattern = @"\\bis\\b";
NSRange range = [text rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) { ... }

This works also for cases like "Is it?" or "It is!", where the word is not surrounded by spaces.

In Swift 2 this would be

let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = "\\bis\\b"
if let range = text.rangeOfString(pattern, options: .RegularExpressionSearch) {
    print ("found:", text.substringWithRange(range))
}