iphone 正则表达式使用(NSRegularExpression)

原文: http://blog.csdn.net/l_ch_g/article/details/9399363

iphone 4.0以后就开始支持正则表达式的使用了,在ios4.0中正则表达式的使用是使用NSRegularExpression类来调用。

下面一个简单的使用正则表达式的一个例子:

1.首先新建一个项目,因为必须使用iso4.0以后的版本,所有我们新建一个iphone项目

 File->new Project 选择:view-based Application 点击 choose。

 

填写项目名字:RegularExpressionTest

 

2.而后打开RegularExpressionTest.m文件定义一个方法叫做:

 

-(void)parseString{

//组装一个字符串,需要把里面的网址解析出来

NSString *urlString=@"sfdsfhttp://www.baidu.com";

 

//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个

 

NSError *error;

 

//http+:[^\\s]* 这个表达式是检测一个网址的。

//<a[^<]+href="course_play.html\?url=([^\"]+)">

//<a[^<]+href="([^\"]+)">

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http+:[^\\s]*" options:0 error:&error];

 

   if (regex != nil) {

   NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0range:NSMakeRange(0, [urlString length])];

  

   if (firstMatch) {

   NSRange resultRange = [firstMatch rangeAtIndex:0];

   

   //从urlString当中截取数据

   NSString *result=[urlString substringWithRange:resultRange];

   //输出结果

   NSLog(@"%@",result);

   }

  

   }

}

posted @ 2015-03-20 19:04  Mr.Greg  阅读(1063)  评论(0编辑  收藏  举报