您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone 開發:用正則表達式擷取字串中的內容

編輯:iOS 開發綜合

起因很簡單:想從一段字串裡取出指定的幾個欄位,直覺就想到正則表達式。於是先寫了下面這版:

第一版:逐個擷取

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的專欄

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved