2015-04-03 224 views
-1

注意:字符串包含字,而不是字符串。我知道rangeOfString方法。查找字符串是否包含字

示例:「由加州蘋果公司設計」不包含「應用程序」一詞,但包含「Apple」。

+0

http://stackoverflow.com/questions/1135524/iphone-whole-word-search有一些不同的要求,而接受的答案實際上並沒有做用戶想要的。在這種情況下,區分大小寫並不重要。 – 2015-04-03 10:20:15

回答

2

在您的正則表達式模式中使用字邊界\\b來匹配整個單詞。

這裏是一個example code

NSString *myText = @"Designed by Apple in California"; 
NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bApple\\b" options:NSRegularExpressionCaseInsensitive error:&error]; 
NSRange textRange = NSMakeRange(0, myText.length); 
NSRange matchRange = [regex rangeOfFirstMatchInString:myText options:0 range:textRange]; 
if (matchRange.location != NSNotFound) 
    NSLog(@"There is a match!"); 
else 
    NSLog(@"No match!"); 

隨着@"\\bApple\\b",你會得到一個 「有一場比賽!」信息。用@"\\bApp\\b",你會得到「不匹配!」。

+0

很好的回答!注意:它會和'Apple'這樣的句子匹配,比如'(Apple - ',這對我來說很棒。 – user1561346 2015-04-03 10:18:49

相關問題