你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iPhone開發--正則表達式獲取字符串中的內容

iPhone開發--正則表達式獲取字符串中的內容

編輯:IOS開發綜合

緣起:

想獲取字符串中指定的字符,考慮用正則表達式,遂寫了如下的代碼:


[cpp] 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]; 
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

思考:

雖然完成了任務,但是這麼寫顯然是低效的,因為每次獲取都需要啟用正則表達式。所以改進如下:

 


[cpp] 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]); 
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

 


注:

我想通過 $1,$2⋯⋯,這種形式獲取,但是沒有成功。不知道哪位高手能實現。


 

摘自 zcl369369的專欄
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved