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.
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])
}
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) {//...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With