Detect whole word in NSStrings

穿精又带淫゛_ 提交于 2019-12-01 18:29:39

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) {//...}

What about

if ([text rangeOfString:@" is " options:NSCaseInsensitiveSearch].location != NSNotFound) { ... }

You could use regular expressions, as suggested, or you could analyze the words linguistically:

NSString *string = @"Here is my string. His isn't a mississippi isthmus. It is...";
__block BOOL containsIs = NO;
[string enumerateLinguisticTagsInRange:NSMakeRange(0, [string length]) scheme:NSLinguisticTagSchemeTokenType options:NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitOther orthography:nil usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop){
    NSString *substring = [string substringWithRange:tokenRange];
    if (containsIs)
        if ([substring isEqualToString:@"n't"])
            containsIs = NO; // special case because "isn't" are actually two separate words
        else
            *stop = YES;
    else
        containsIs = [substring isEqualToString:@"is"];
}];
NSLog(@"'%@' contains 'is': %@", string, containsIs ? @"YES" : @"NO");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!