NSRegularExpression正则表达式的使用

ios sdk 4.0开始支持正则表达式了,主要的两个类是:

用于匹配的NSRegularExpression和用于存储匹配结果的NSTextCheckingResult。

用法如下:

 

    NSMutableString *sch = [NSMutableString stringWithString:@"中文<img  width=\"296\"> 标题title </img>语言<img  width=\"296\"> 标题title </img>"];
    NSError *err;
    NSString *pattern = @"<img([^<]+)";
   
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&err];
   
    NSArray *matches =     [reg matchesInString:sch options:NSMatchingCompleted range:NSMakeRange(0, [sch length])];
   
    for (NSTextCheckingResult *match in matches) {


        NSRange range = [match range];
        NSLog(@"%d,%d,%@",range.location,range.length,[sch substringWithRange:range]);


        //capture groups
        for (int i = 0; i< [match numberOfRanges]; i++) {
            NSRange range1 = [match rangeAtIndex:i];
            NSLog(@"%d :%@",i,[sch substringWithRange:range1]);
        }
       
    }

   [reg replaceMatchesInString:sch options:NSMatchingCompleted range:NSMakeRange(0, [sch length]) withTemplate:@"100"];
   
    NSLog(@"%@",sch);

输出结果:

2011-09-01 17:52:22.983 StringTest[7710:207] 2,27,<img  width="296"> 标题title
2011-09-01 17:52:22.984 StringTest[7710:207] 0 :<img  width="296"> 标题title
2011-09-01 17:52:22.985 StringTest[7710:207] 1 :  width="296"> 标题title
2011-09-01 17:52:22.985 StringTest[7710:207] 37,27,<img  width="296"> 标题title
2011-09-01 17:52:22.986 StringTest[7710:207] 0 :<img  width="296"> 标题title
2011-09-01 17:52:22.986 StringTest[7710:207] 1 :  width="296"> 标题title
2011-09-01 17:52:22.993 StringTest[7710:207] 中文100</img>语言100</img>

 

更多用法可以查看官方的帮助文档

你可能感兴趣的:(正则表达式,职场,休闲)