[cpp] NSString *htmlStr = @"oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit"; NSString *regexString = @"oauth_token=(+)"; 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=(+)"; 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
1a1de4ed4fca40599c5e5cfe0f4fba973118a84ad910967990ba50f5649632fa
foolshit