iPhone SDK 4.0正则表达式是本文要介绍的内容,主要是来学习正则表达式的使用,具体内容先来看详细内容。在iPhone程序使用正则表达式,主要以来于NSRegularExpression类。废话不多说了,下面给个利用正则表达式来替换文本内容的代码:
- //以替换html元素<a href="Xxxx">Yyyy</a>中的标签为例。
- - (NSString *)removeTag:(NSString *)srcStr {NSError *error = nil;
- NSMutableString *dest = [NSMutableString stringWithCapacity:0];
- NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<a href=\".+?\">(.+?)</a>"
- options:NSRegularExpressionCaseInsensitive error:&error];
- NSRegularExpression *regex2 = [[NSRegularExpression alloc] initWithPattern:@"(?<=>).*?(?=</a>)"
- options:NSRegularExpressionCaseInsensitive error:nil];
- NSUInteger numberOfMatches = [regex numberOfMatchesInString:srcStr options:0 range:NSMakeRange(0, [srcStr length])];
- if (numberOfMatches != 0) {[dest appendString:srcStr];
- /*以下几行是一个方法调用,有点长就分行了(本人一般不习惯分行的,即使巨长的一个方法调用,但是这个调用中有个方法定义做参数,所以……)。*/
- [regex enumerateMatchesInString:srcStr options:0 range:NSMakeRange(0, [srcStr length])
- usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
- {NSString *resultString = [srcStr substringWithRange:[result range]];
- NSString *link = [resultString substringWithRange:[[regex2 firstMatchInString:resultString options:0
- range:NSMakeRange(0, [resultString length])] range]];
- [dest replaceCharactersInRange:[result range] withString:link];
- }
- ];
- return
- [dest stringByReplacingOccurrencesOfString:@"<br />" withString:@""];
- }else
- {return [srcStr stringByReplacingOccurrencesOfString:@"<br />" withString:@""];
- }
- }//调用
- - (void)viewDidLoad {NSLog([self performSelector:@selector(removeTag:) withObject:@"this is <a href=\"www.baidu.com\">a</a> test!"]);
- }
输出结果:
- this is a test!
小结:详解iPhone SDK 4.0正则表达式的内容介绍完了,希望通过本文的学习能对你有所帮助!