在工程中需要從 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中的貪心算法和非貪心算法 - 注意
NSTextCheckingResult的numberOfRanges的用法。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