iOS 中NSRegularExpression 的使用

1 我们可以获取符合某种正则表达是的字符在整个字符串中的位置

如:获取图片url链接中的图片大小的字符的位置,图片大小格式为**_**  '*'标识任何0-9的数字

   NSError *error;
    NSString *regularStr = @"image/\\d{2,3}_\\d{2,3}/";
    NSRegularExpression *espress = [NSRegularExpression regularExpressionWithPattern:regularStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *arrayofRange = [espress matchesInString:url options:0 range:NSMakeRange(0, url.length)];
    if (arrayofRange.count == 0) {
        return url;
    }
    NSTextCheckingResult *result = arrayofRange.firstObject;

///位置
NSInteger location = result.range.location

2 我们可以替换字符串中符合某种正则表达的字符

如:替换链接中的0-9 像素为3像素

 NSString * regExpStr = @"size=\"[0-9]{1,2}px\"";
            NSString * replacement = @"size=\"3px\"";
            
            // 创建 NSRegularExpression 对象,匹配 正则表达式
            NSRegularExpression *regExp =
            [[NSRegularExpression alloc] initWithPattern:regExpStr
                                                 options:NSRegularExpressionCaseInsensitive
                                                   error:nil];
            
            contentStr = [regExp stringByReplacingMatchesInString:contentStr
                                                          options:NSMatchingReportProgress
                                                            range:NSMakeRange(0, contentStr.length)
                                                     withTemplate:replacement];

猜你喜欢

转载自blog.csdn.net/LIUXIAOXIAOBO/article/details/114526316