IOS利用NSRegularExpression写正则

来源:互联网 发布:推广软件通科 编辑:程序博客网 时间:2024/06/03 03:35

IOS利用NSRegularExpression写正则

by lesvio


NSString *yourString = @"abcd awesd asiikd aootood";NSError *error = NULL;NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"a(\\w+)d" options:NSRegularExpressionCaseInsensitive error:&error];   [regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){     NSString *insideString = [yourString substringWithRange:[match rangeAtIndex:1]];     NSLog(@"%@",insideString);}];

输出:

2014-04-27 09:50:10.558 Test2[13772:60b] bc

2014-04-27 09:50:10.559 Test2[13772:60b] wes

2014-04-27 09:50:10.560 Test2[13772:60b] siik

2014-04-27 09:50:10.560 Test2[13772:60b] ootoo


还有一个写法

NSRegularExpression *regex = [NSRegularExpressionregularExpressionWithPattern:@"stack(.*).html"options:0error:NULL];

NSString *str = @"stackoverflow.html";

NSTextCheckingResult *match = [regex firstMatchInString:stroptions:0range:NSMakeRange(0, [strlength])];

NSString *insideString = [str substringWithRange:[match rangeAtIndex:1]];

NSLog(@"%@",insideString);


输出:

2014-04-27 09:55:01.299 Test2[13838:60b] overflow


还有一种更好用的
NSString *string = @"lalala (我们都是光荣的程序员) 呵呵";NSError *error = nil;NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^;]*\\)" options:NSRegularExpressionCaseInsensitive error:&error];NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];NSString *insideString = [string substringWithRange:[match rangeAtIndex:0]];NSLog(@"%@",insideString);NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];NSLog(@"%@", modifiedString);

输出:

2014-04-27 10:01:03.198 Test2[13926:60b] (我们都是光荣的程序员)

2014-04-27 10:01:03.198 Test2[13926:60b] lalala  呵呵



0 0
原创粉丝点击