查找字符串是否包含单词
Find if string contains word
注意:字符串包含单词,而不是字符串。我知道 rangeOfString
方法。
示例:"Designed by Apple in California" 不包含 "App" 单词,但包含 "Apple".
在您的正则表达式模式中使用单词边界 \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"
,您将收到一条 "There is a match!" 消息。使用 @"\bApp\b"
,您将获得 "No match!"。
注意:字符串包含单词,而不是字符串。我知道 rangeOfString
方法。
示例:"Designed by Apple in California" 不包含 "App" 单词,但包含 "Apple".
在您的正则表达式模式中使用单词边界 \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"
,您将收到一条 "There is a match!" 消息。使用 @"\bApp\b"
,您将获得 "No match!"。