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
    

實際開發(fā)過程中遇到的坑:

  • | 在正則表達式中是元字符,所以在寫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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容