简体   繁体   中英

Detecting if NSString contains chinese characters

I have an UISearchBar , and I want my data to be sorted by pinYin if the user inputs English, and sorted by the characters themselves when the user inputs Chinese characters.

Is there something like

if (searchText isKindofClass: UTF-8String) 

to detect if an NSString contains Chinese characters?

You can use a NSRegularExpression to search for "character families" :

https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

http://userguide.icu-project.org/strings/regexp

They give an example of \\p{script=cyrillic} , I guess by searching a little you'll find something related to Chinese.

If you use \\p{script=Han} to detecting Chinese, be sure to add ' \\ ' before \\p . So it is like

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\\p{Script=Han}" options:NSRegularExpressionCaseInsensitive error:&error];

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