iOS中正则表达式的运用示例代码

2020-01-21 00:45:48刘景俊

3.替换字符串


//返回与模板字符串替换的匹配正则表达式的新字符串
- (NSString *)stringByReplacingMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;

//返回替换的个数
- (NSUInteger)replaceMatchesInString:(NSMutableString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;

//自定义替换功能
- (NSString *)replacementStringForResult:(NSTextCheckingResult *)result inString:(NSString *)string offset:(NSInteger)offset template:(NSString *)templ;

//通过根据需要添加反斜杠转义来返回模板字符串,以保护符合模式元字符的任何字符
+ (NSString *)escapedTemplateForString:(NSString *)string;

使用示例


 NSString *str = @"aabbcccdeaargdo14141214aaghfh56821d3gad4";
 NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"aa" options:NSRegularExpressionCaseInsensitive error:NULL];
 if (expression != nil) {
  //匹配到的第一组
  NSTextCheckingResult *firstMatch = [expression firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  NSRange range = [firstMatch rangeAtIndex:0];
  NSString *result = [str substringWithRange:range];
  NSLog(@"匹配到的第一组:%@",result);
  //匹配到的个数
  NSInteger number = [expression numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  NSLog(@"匹配到的个数%ld",number);
  //配到到的所有数据
  NSArray *allMatch = [expression matchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  for (int i = 0; i < allMatch.count; i ++) {
   NSTextCheckingResult *matchItem = allMatch[i];
   NSRange range = [matchItem rangeAtIndex:0];
   NSString *result = [str substringWithRange:range];
   NSLog(@"匹配到的数据:%@",result);
  }
  //匹配到第一组的位置
  NSRange firstRange = [expression rangeOfFirstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  NSLog(@"匹配到第一组的位置:开始位置%lu--长度%lu",(unsigned long)firstRange.location,(unsigned long)firstRange.length);
  
  //替换字符串
  NSString *resultStr = [expression stringByReplacingMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"];
  NSLog(@"替换后的字符串:%@",resultStr);
  
  NSInteger resultNum = [expression replaceMatchesInString:[str mutableCopy] options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"];
  NSLog(@"替换的个数;%ld",(long)resultNum);
 }

打印log:
2017-08-13 23:28:53.898 NSRegularExpressionDemo[82046:8220904] 匹配到的第一组:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的个数3
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到第一组的位置:开始位置0--长度2
NSRegularExpressionDemo[82046:8220904] 替换后的字符串:bbbbbbcccdebbbbrgdo14141214bbbbghfh56821d3gad4
NSRegularExpressionDemo[82046:8220904] 替换的个数;3