简体   繁体   中英

Example of using NSRegularExpression to detect if string contains Cyrillic

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

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:@"привет"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM