在工程中需要從 protocol://customProtocol|title=this is title|message=this is message|shareUrl=this is url
字符串中分別拿到 title窟坐、message狂秦、shareUrl 的內(nèi)容,因為字符串的格式是固定的,自然而然的想到了正則表達(dá)式, 當(dāng)然也可以對字符串按照 |
分隔撵颊,然后再按 =
分隔之后獲取指定的值。
最終實現(xiàn)代碼:
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 根據(jù)自己需求選擇
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ā)過程中遇到的坑:
-
|
在正則表達(dá)式中是元字符,所以在寫parten 中需要用\
轉(zhuǎn)義字符, 但在OC中\
也是轉(zhuǎn)義字符袜炕,所以最后需要\\|
來表示匹配|
。 - 正則默認(rèn)是貪心的献酗,所以需要在
.*
后加上?
正則表達(dá)式re中的貪心算法和非貪心算法 - 注意
NSTextCheckingResult
的numberOfRanges
的用法寝受。rangeAtIndex
為0 是匹配最長的結(jié)果。
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.
最后推薦一個比較友好的正則表達(dá)式在線測試網(wǎng)站Oneline regex test