正则匹配 NSRegularExpression
1.正则中使用了\d
,\b
等,需要对 \ 做转义,使用转义字符\
进行转义
2.NSRegularExpression
初始化方法中的options
设置为kNilOptions
时区分大小写,严格验证;设置NSRegularExpressionCaseInsensitive
不区分大小写,其它设置参考系统API
初始化
/// 初始化NSRegularExpression,如果出错则会返回nil,并带有error
/// @param pattern 正则表达式
/// @param options 模式选项, 设置kNilOptions时区分大小写
/// @parma error 错误
+ (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;
关于NSRegularExpressionOptions
typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {
NSRegularExpressionCaseInsensitive = 1 << 0, /* Match letters in the pattern independent of case. */
NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, /* Ignore whitespace and #-prefixed comments in the pattern. */
NSRegularExpressionIgnoreMetacharacters = 1 << 2, /* Treat the entire pattern as a literal string. */
NSRegularExpressionDotMatchesLineSeparators = 1 << 3, /* Allow . to match any character, including line separators. */
NSRegularExpressionAnchorsMatchLines = 1 << 4, /* Allow ^ and $ to match the start and end of lines. */
NSRegularExpressionUseUnixLineSeparators = 1 << 5, /* Treat only \n as a line separator (otherwise, all standard line separators are used). */
NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */
};
返回所有匹配结果
/// 返回所有匹配结果,适合从一段字符串提取我们想要匹配的所有数据
- (NSArray<NSString *> *)matchesWithPattern:(NSString *)pattern validateString:(NSString *)validate {
NSError *error = NULL;
// options: NSRegularExpressionCaseInsensitive 不区分大小写
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (error) {
NSLog(@"matchesWithPattern error: %@", error);
return @[];
}
NSArray<NSTextCheckingResult *> *results = [regex matchesInString:validate options:0 range:NSMakeRange(0, validate.length)];
NSMutableArray *mDatas = @[].mutableCopy;
[results enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *mathedStr = [validate substringWithRange:obj.range];
[mDatas addObject:mathedStr];
}];
return mDatas;
}
测试用例:
NSString *pattern = @"^(10001|10002)$";
NSString *validate = @"10001";
NSArray *matches = [self matchesWithPattern:pattern validateString:validate];
NSLog(@"匹配结果:%@", matches);
打印结果:
匹配成功:(
10001
)
获取第1个匹配的结果
/// 获取第1个匹配的结果
- (NSString *)firstMatchWithPattern:(NSString *)pattern validateString:(NSString *)validate {
NSError *error = NULL;
// options: kNilOptions 区分大小写,严格验证
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:&error];
if (error) {
NSLog(@"firstMatchWithPattern error: %@", error);
return @"";
}
NSTextCheckingResult *result = [regex firstMatchInString:validate options:0 range:NSMakeRange(0, validate.length)];
NSString *mathedStr = [validate substringWithRange:result.range];
return mathedStr;
}
测试用例:
// \d, \b等需要对\转义,需要使用转义字符进行转义
NSString *pattern = @"runoob(?=[\\d+])";
NSString *validate = @"runoob12runoobdrunooB3";
NSString *firstMatch = [self firstMatchWithPattern:pattern validateString:validate];
NSLog(@"匹配结果:%@", firstMatch);
打印结果:
匹配成功:runoob
获取匹配的数量
/// 获取匹配的数量
- (NSUInteger)numberOfMatchesWithPattern:(NSString *)pattern validateString:(NSString *)validate {
NSError *error = NULL;
// options: kNilOptions 区分大小写,严格验证
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:&error];
if (error) {
NSLog(@"firstMatchWithPattern error: %@", error);
return 0;
}
NSUInteger number = [regex numberOfMatchesInString:validate options:kNilOptions range:NSMakeRange(0, validate.length)];
return number;
}
测试用例:
// \d, \b等需要对\转义,需要使用转义字符进行转义
NSString *pattern = @"runoob(?=[\\d+])";
NSString *validate = @"runoob12runoobdrunooB3";
NSUInteger number = [self numberOfMatchesWithPattern:pattern validateString:validate];
NSLog(@"匹配数量:%lu", (unsigned long)number);
打印结果:
匹配数量:1
字符串正则替换
/// 字符串正则替换
- (NSString *)matchReplaceWithPattern:(NSString *)pattern validateStr:(NSString *)validate replacingStr:(NSString *)replacingStr {
NSError *error = NULL;
// options: kNilOptions 区分大小写,严格验证
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:&error];
if (error) {
NSLog(@"firstMatchWithPattern error: %@", error);
return validate;
}
NSString *newStr = [regex stringByReplacingMatchesInString:validate options:0 range:NSMakeRange(0, validate.length) withTemplate:replacingStr];
return newStr;
}
测试用例:
NSString *replacePattern = @"[0-9]+";
NSString *validateStr = @"12-ab-3-c";
NSString *replacingStr = @"ufo";
NSString *newStr = [self matchReplaceWithPattern:replacePattern validateStr:validateStr replacingStr:replacingStr];
NSLog(@"替换后:%@", newStr);
打印结果:
替换后:ufo-ab-ufo-c
网友评论