起因很簡單:想從一段字串裡取出指定的幾個欄位,直覺就想到正則表達式。於是先寫了下面這版:
NSString *htmlStr = @"oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97"
@"&oauth_token_secret=3118a84ad910967990ba50f5649632fa"
@"&name=foolshit";
NSString *regexString = @"oauth_token=(\\w+)&oauth_token_secret=(\\w+)&name=(\\w+)";
NSString *matchedString1 = [htmlStr stringByMatching:regexString capture:1L];
NSString *matchedString2 = [htmlStr stringByMatching:regexString capture:2L];
NSString *matchedString3 = [htmlStr stringByMatching:regexString capture:3L];
結果如預期取出了三個值:
1a1de4ed4fca40599c5e5cfe0f4fba97 3118a84ad910967990ba50f5649632fa foolshit
任務是完成了,但這樣寫顯然沒效率——每抓一個 capture group 就要重新跑一次正則引擎,同一段字串被掃了三遍。於是改進如下:
NSArray *matchArray = NULL; matchArray = [htmlStr componentsMatchedByRegex:regexString]; NSLog(@"matchedString0 is %@", [matchArray objectAtIndex:0]); NSLog(@"matchedString1 is %@", [matchArray objectAtIndex:1]); NSLog(@"matchedString2 is %@", [matchArray objectAtIndex:2]); NSLog(@"matchedString3 is %@", [matchArray objectAtIndex:3]);
結果:
oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit 1a1de4ed4fca40599c5e5cfe0f4fba97 3118a84ad910967990ba50f5649632fa foolshit
可以明顯看出差別:index 0 是整段比對結果,index 1 之後才依序對應各個括號群組。這個「0 為全匹配」的慣例與多數正則實作一致,取值時別忘了位移一格的關係。
第一,stringByMatching:capture: 與 componentsMatchedByRegex: 並非 Foundation 的原生 API,而是來自 RegexKit 一類的第三方類別。使用時必須先引入對應函式庫,否則編譯期就會找不到方法。
第二,如果不想引入外部函式庫,從 iOS 4 起系統已內建 NSRegularExpression,可以直接用 firstMatchInString:options:range: 搭配 rangeAtIndex: 取得各群組範圍,再用 substringWithRange: 取出字串,效果相同且不必多裝套件。
另外,原本我想用 $1, $2 ... 這種樣板展開的形式來取值,嘗試後沒有成功。若哪位先進有可行的做法,還請指教。
摘自 zcl369369的專欄