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

时间:2014-03-08 22:41:08

标签: ios iphone regex nsstring nsregularexpression

我查看了NSRegularExpression上的Apple reference,并了解为了查看该字符串是否为西里尔字母,我应该使用\p{script=cyrillic}。但是,我无法在参考指南或位于SO中的answer中找到如何完成此操作的实际示例。我理想的目标是:

if (string contains \p{script=cyrillic}){
    return YES;
    }
else {
    return NO;
    }

1 个答案:

答案 0 :(得分: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;
}

然后用法(NSString的类别可能更好?)

NSLog(@"hello: %hhd", [self containsCyrillic:@"hello"]);
NSLog(@"привет: %hhd", [self containsCyrillic:@"привет"]);