Example of using NSRegularExpression to detect if string contains Cyrillic

风流意气都作罢 提交于 2019-12-08 09:17:53

问题


I looked into the Apple reference on NSRegularExpression, and understand that in order see if the string is Cyrillic I should use \p{script=cyrillic}. However, I have not been able to find an actual example of how this is done in the reference guide or in an answer located in SO. What I would ideally like to achieve is:

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

回答1:


Maybe (I am an iOS programming newbie):

- (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;
}

And then the usage (a category for NSString would probably be better?)

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


来源:https://stackoverflow.com/questions/22275994/example-of-using-nsregularexpression-to-detect-if-string-contains-cyrillic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!