您的位置:首页 > 移动开发 > IOS开发

IOS正则表达式

2013-09-04 17:37 323 查看
ios从4.0开始支持正则表达式。具体涉及到的类是:
NSRegularExpression
NSTextCheckingResult
有了这个内置的ios正则表达式函数,可以不用RegexKitLite了。现在比较强的正则库是PCRE的,mac上PCRE的实现见: http://regexkit.sourceforge.net/
两个例子说明一下NSRegularExpression的用法:

[cpp]
view plaincopy

-(void)parseString{
//组装一个字符串,需要把里面的网址解析出来
NSString *urlString=@"sfdsfhttp://www.baidu.com";

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

NSError *error;

//http+:[^\\s]* 这个表达式是检测一个网址的。
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http+:[^\\s]*" options:0 error:&error];

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

if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];

//从urlString当中截取数据
NSString *result=[urlString substringWithRange:resultRange];
//输出结果
NSLog(@"%@",result);
}

}
}

NSRegularExpression功能还是比较强大的,支持正则嵌套分组,下面是例子:

[cpp]
view plaincopy

NSString * tmp = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dreamcafe.rtf" ofType:nil]
encoding:NSUTF8StringEncoding
error:nil];

// NSRange r;
NSString *regExStr = @"hbhWxTime[\"\']><.*?>(.+?)<";
NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExStr
options:NSRegularExpressionCaseInsensitive
error:&error];

__block NSMutableArray * timeTimes = [NSMutableArray array];
[regex enumerateMatchesInString:tmp options:0 range:NSMakeRange(0, [tmp length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(@"timeTimes = %@",[tmp substringWithRange:[result rangeAtIndex:1]]);

[timeTimes addObject:[tmp substringWithRange:[result rangeAtIndex:1]]];
}];

/*注释:

[result rangeAtIndex:0] yuresult.range 等价

*/

说明:

匹配结果:

NSTextCheckingResult

!!!用range来标示匹配到的每一个子表达式/分组的。既通过substringWithRange:才能获取到某个子表达式匹配到的字符串

range
resultType
numberOfRanges 匹配到的分组/子表达式个数
– rangeAtIndex: 获取第几个子表达式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: