查找字符串是否包含单词[duplicate]

时间:2022-04-10 21:46:57

This question already has an answer here:

这个问题在这里已有答案:

Note: String contains word, not string. I do know about rangeOfString method.

注意:字符串包含单词,而不是字符串。我知道rangeOfString方法。

Example: "Designed by Apple in California" is not contains "App" word, but contains "Apple".

示例:“由Apple在加利福尼亚设计”不包含“App”字样,但包含“Apple”。

1 个解决方案

#1


2  

Use word boundary \\b in your regex patterns to match whole words.

在正则表达式模式中使用单词边界\\ b来匹配整个单词。

Here is an 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!");

With @"\\bApple\\b", you will get a "There is a match!" message. With @"\\bApp\\b", you will get "No match!".

使用@“\\ bApple \\ b”,您将获得“有匹配!”信息。使用@“\\ bApp \\ b”,您将获得“不匹配!”。

#1


2  

Use word boundary \\b in your regex patterns to match whole words.

在正则表达式模式中使用单词边界\\ b来匹配整个单词。

Here is an 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!");

With @"\\bApple\\b", you will get a "There is a match!" message. With @"\\bApp\\b", you will get "No match!".

使用@“\\ bApple \\ b”,您将获得“有匹配!”信息。使用@“\\ bApp \\ b”,您将获得“不匹配!”。