Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 299
Scott Avatar asked Nov 05 '13 09:11

Scott


2 Answers

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, .CaseInsensitiveSearch]) {
    print ("found:", text.substringWithRange(range))
}

Swift 3:

let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = "\\bis\\b"
if let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
    print ("found:", text.substring(with: range))
}

Swift 4:

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

Swift 5 (using the new raw string literals):

let text = "Here is my string. His isn't a mississippi isthmus. It is..."
let pattern = #"\bis\b"#
if let range = text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
    print ("found:", text[range])
}
like image 163
Martin R Avatar answered Oct 06 '22 01:10

Martin R


Use NSRegularExpressionSearch option with \b to match word boundary characters.

Like this:

NSString *string = @"Here is my string. His isn't a mississippi isthmus. It is...";
if(NSNotFound != [string rangeOfString:@"\\bis\\b" options:NSRegularExpressionSearch].location) {//...}
like image 39
Michał Ciuba Avatar answered Oct 05 '22 23:10

Michał Ciuba