iOS 正则表达式匹配子串

2018-01-08  本文已影响514人  Ever_Blacks

在工程中需要从 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
    

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

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

上一篇 下一篇

猜你喜欢

热点阅读