详解iPhone SDK 4.0正则表达式
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!"]); }
输出结果:
相关推荐
liuxudong00 2020-11-19
章鱼之家 2020-10-29
leitingdulante 2020-10-21
xuegangic 2020-10-17
硬币0 2020-10-15
ZuoYanDeHuangHun 2020-09-18
chsoft 2020-09-17
MatrixHero 2020-08-20
XxZproject 2020-08-10
定格 2020-08-15
Mryiyi 2020-08-07
ydc0 2020-07-30
yechen00 2020-07-25
孝平 2020-07-18
ntfsformac 2020-06-23
好好学习天天 2020-06-12
Charliewolf 2020-06-05
MAC2007 2020-06-04
fanxiaoxuan 2020-06-03