如何检测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) { ... }
,但它检测的字符不是单词。
答案 0 :(得分:12)
使用“正则表达式”搜索“单词边界模式”\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?"
或"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))
}
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])
}
答案 1 :(得分:1)
使用NSRegularExpressionSearch
\b
选项匹配字边界字符。
像这样:
NSString *string = @"Here is my string. His isn't a mississippi isthmus. It is...";
if(NSNotFound != [string rangeOfString:@"\\bis\\b" options:NSRegularExpressionSearch].location) {//...}
答案 2 :(得分:0)
怎么样?
if ([text rangeOfString:@" is " options:NSCaseInsensitiveSearch].location != NSNotFound) { ... }
答案 3 :(得分: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");