緣起:
想擷取字串中指定的字元,考慮用Regex,遂寫了如下的代碼:
[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
思考:
雖然完成了任務,但是這麼寫顯然是低效的,因為每次擷取都需要啟用Regex。所以改進如下:
[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的專欄