5

如何检测 NSString 是否包含特定单词,例如is.

如果 NSString 是Here is my string. His isn't a mississippi isthmus. It is...? 该方法应该检测单词is并返回YES

但是,如果 NSString 是His isn't a mississipi isthmus,它应该返回NO

我尝试使用if ([text rangeOfString:@"is" options:NSCaseInsensitiveSearch].location != NSNotFound) { ... },但它检测字符而不是单词。

4

4 回答 4

15

使用带有“单词边界模式”的“正则表达式”搜索\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) { ... }

这也适用于"Is it?"or之类的情况"It is!",其中单词没有被空格包围。

Swift 2中,这将是

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))
}

斯威夫特 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))
}

斯威夫特 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(使用新的原始字符串文字):

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])
}
于 2013-11-05T09:21:46.233 回答
1

使用NSRegularExpressionSearch选项 with\b匹配单词边界字符。

像这样:

NSString *string = @"Here is my string. His isn't a mississippi isthmus. It is...";
if(NSNotFound != [string rangeOfString:@"\\bis\\b" options:NSRegularExpressionSearch].location) {//...}
于 2013-11-05T09:22:09.793 回答
0

关于什么

if ([text rangeOfString:@" is " options:NSCaseInsensitiveSearch].location != NSNotFound) { ... }
于 2013-11-05T09:06:28.663 回答
0

您可以按照建议使用正则表达式,也可以从语言上分析单词:

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");
于 2013-11-05T09:42:08.027 回答