iOS 正则表达式匹配子串

在工程中需要从 protocol://customProtocol|title=this is title|message=this is message|shareUrl=this is url 字符串中分别拿到 title、message、shareUrl 的内容,因为字符串的格式是固定的,自然而然的想到了正则表达式, 当然也可以对字符串按照 | 分隔,然后再按 = 分隔之后获取指定的值。

最终实现代码:

    NSString *testStr = @"protocol://customProtocol|title=this is title|message=this is message|shareUrl=this is url";
    NSString *parten = @"\\|title=(.*?)\\|message=(.*?)\\|shareUrl=(.*)$";
    NSError *error = nil;
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:NSRegularExpressionCaseInsensitive error:&error]; //options 根据自己需求选择
    
    NSArray *matches = [reg matchesInString:testStr options:NSMatchingReportCompletion range:NSMakeRange(0, testStr.length)];

    for (NSTextCheckingResult *match in matches) {
        //NSRange matchRange = [match range]; //获取所匹配的最长字符串
        for (int i = 0; i < match.numberOfRanges; i++) {
            NSRange matchRange = [match rangeAtIndex:i];
            NSString *matchString = [testStr substringWithRange:matchRange];
            NSLog(@"index:%@, %@", @(i) matchString);
        }
    }
    
    output:
    index:0, |title=this is title|message=this is message|shareUrl=this is url
    index:1, this is title
    index:2, this is message
    index:3, this is url
    

实际开发过程中遇到的坑:

  • | 在正则表达式中是元字符,所以在写parten 中需要用 \ 转义字符, 但在OC中 \ 也是转义字符,所以最后需要 \\| 来表示匹配 |
  • 正则默认是贪心的,所以需要在 .* 后加上 ? 正则表达式re中的贪心算法和非贪心算法
  • 注意NSTextCheckingResultnumberOfRanges的用法。 rangeAtIndex 为0 是匹配最长的结果。

A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups). The range at index 0 always matches the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. rangeWithName: can be used with named regular expression capture groups.

最后推荐一个比较友好的正则表达式在线测试网站Oneline regex test

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。