使用NSRegularExpression检测字符串是否包含西里尔文的示例

das*_*ist 1 regex iphone nsstring ios nsregularexpression

我看着苹果基准NSRegularExpression,并理解,为了看到如果字符串是西里尔我应该使用\p{script=cyrillic}.但是,我无法在参考指南或SO 中的答案中找到如何完成此操作的实际示例.我理想的目标是:

if (string contains \p{script=cyrillic}){
    return YES;
    }
else {
    return NO;
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*ber 6

也许(我是iOS编程新手):

- (BOOL)containsCyrillic:(NSString*)str
{
    NSString* const pattern = @"\\p{script=cyrillic}+";
    NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
                                                                      options:0
                                                                        error:nil];
    NSRange range = NSMakeRange(0, [str length]);
    return [regex numberOfMatchesInString:str
                                  options:0
                                    range:range] > 0;
}
Run Code Online (Sandbox Code Playgroud)

然后使用(一个类别NSString可能会更好?)

NSLog(@"hello: %hhd", [self containsCyrillic:@"hello"]);
NSLog(@"??????: %hhd", [self containsCyrillic:@"??????"]);
Run Code Online (Sandbox Code Playgroud)