码迷,mamicode.com
首页 > 其他好文 > 详细

iPhone开发--正则表达式获取字符串中的内容

时间:2015-03-13 18:38:00      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

缘起:

想获取字符串中指定的字符,考虑用正则表达式,遂写了如下的代码:

 

[cpp] view plaincopy
 
  1. NSString *htmlStr = @"oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit";  
  2. NSString *regexString = @"oauth_token=(\\w+)&oauth_token_secret=(\\w+)&name=(\\w+)";  
  3. NSString *matchedString1 = [htmlStr stringByMatching:regexString capture:1L];  
  4. NSString *matchedString2 = [htmlStr stringByMatching:regexString capture:2L];  
  5. NSString *matchedString3 = [htmlStr stringByMatching:regexString capture:3L];  

获取的结果如下:

 

1a1de4ed4fca40599c5e5cfe0f4fba97

3118a84ad910967990ba50f5649632fa

foolshit

思考:

虽然完成了任务,但是这么写显然是低效的,因为每次获取都需要启用正则表达式。所以改进如下:

 

[cpp] view plaincopy
 
  1. NSArray *matchArray = NULL;     
  2. matchArray = [htmlStr componentsMatchedByRegex:regexString];  
  3. NSLog(@"matchedString0 is %@", [matchArray objectAtIndex:0]);  
  4. NSLog(@"matchedString1 is %@", [matchArray objectAtIndex:1]);  
  5. NSLog(@"matchedString2 is %@", [matchArray objectAtIndex:2]);  
  6. NSLog(@"matchedString3 is %@", [matchArray objectAtIndex:3]);  

 

获取的结果如下:

oauth_token=1a1de4ed4fca40599c5e5cfe0f4fba97&oauth_token_secret=3118a84ad910967990ba50f5649632fa&name=foolshit

1a1de4ed4fca40599c5e5cfe0f4fba97

3118a84ad910967990ba50f5649632fa

foolshit

 

注:

我想通过 $1,$2??,这种形式获取,但是没有成功。不知道哪位高手能实现。

附录:忘记写需要加入第三方类库了,⊙﹏⊙b汗,多亏有人留言提醒。

1.下载RegexKitLite类库,解压出来会有一个例子包及2个文件(RegexKitLite文件夹下的两个文件),其实用到的就这2个文件,添加到工程中。

2.工程中添加libicucore.dylib frameworks。

 

转:http://blog.csdn.net/zcl369369/article/details/7181807

iPhone开发--正则表达式获取字符串中的内容

标签:

原文地址:http://www.cnblogs.com/ygm900/p/4335662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!