iOS 中文字符判断 正则NSRegularExpression 谓词NSPredicate 和 NSRange
原文:https://www.cnblogs.com/pruple/p/7450654.html
#pragma mark - 中文字符判断
// 正则匹配是否包含中文
- (BOOL)validateContainsChinese:(NSString *)content
{
// ^[\u4e00-\u9fa5] 以中文开头 的字符串
// [\u4e00-\u9fa5] 包含中文
NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
initWithPattern:@"^[\u4e00-\u9fa5]"
options:NSRegularExpressionCaseInsensitive
error:nil];
return ([regularexpression numberOfMatchesInString:content
options:NSMatchingReportProgress
range:NSMakeRange(0, content.length)] > 0);
}
// 谓词匹配是否为全中文
- (BOOL)validateAllChinese:(NSString *)content
{
NSString *regEx = @"^[\u4e00-\u9fa5]+$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
return [predicate evaluateWithObject:content];
}
// 谓词匹配包含中文
- (BOOL)validateContainsChineseT:(NSString *)content
{
NSString *regEx = @".+[\u4e00-\u9fa5].+"; // @"^[\u4e00-\u9fa5].*" - ^为匹配中文开始
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
return [predicate evaluateWithObject:content];
}
// 匹配包含中文:利用rangeOfString:option:直接查找
- (BOOL)validateRangeContainsChinese:(NSString *)content
{
NSString *regEx = @".*[\u4e00-\u9fa5].*";
NSRange range = [content rangeOfString:regEx options:NSRegularExpressionSearch];
return range.length;
}
// 匹配全是中文:利用rangeOfString:option:直接查找
- (BOOL)validateRangeAllChinese:(NSString *)content
{
NSString *regEx = @"^[\u4e00-\u9fa5]+S";
NSRange range = [content rangeOfString:regEx options:NSRegularExpressionSearch];
return range.length;
}
网友评论