iPhone开发--正则表达式获取字符串中的内容
缘起:
想获取字符串中指定的字符,考虑用正则表达式,遂写了如下的代码:
[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⋯⋯,这种形式获取,但是没有成功。不知道哪位高手能实现。
相关新闻>>
- 发表评论
-
- 最新评论 更多>>