0.Foundation框架提供的正则表达式的实现类

1.正则表达式的开源实现类:RegexKitLite (MRC,在ARC的工程中要对其.m文件的编译设置-fno-objc-arc)
使用这个类,需要导入依赖库:libicucore.dylib

2.入门推荐学习网站:http://www.jb51.net/tools/zhengze.html点击打开链接

一、Foundation框架提供的正则表达式的实现类


NSString *text = @"张三:010-88669900,李四电话010-55443322发送0731-8373834垃圾费";

//1、定义正则表达式
NSString *regex = @"\\d{3,4}-\\d{7,8}";

//2、创建正则表达式实现对象
NSRegularExpression *regexExpre = [[NSRegularExpression alloc] initWithPattern:regex options:NSRegularExpressionCaseInsensitive error:nil];

//3、查找符合正则表达式的子字符串
NSArray *items = [regexExpre matchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, text.length)];

//4.循环遍历查找出来的结果
for (NSTextCheckingResult *result in items) {
//符合表达式的字符串的范围
NSRange range = [result range];

NSString *matchString = [text substringWithRange:range];
NSLog(@"%@",matchString);
}


二、利用开源类RegexKitLite实现,比较简单
//需求1:找以l开头的单词
NSString *text = @"array love like pig cat l72348";

//NSString *regex = @"\\bl\\w*\\b";

NSString *regex = @"\\bl[a-zA-Z]*\\b";

NSArray *items = [text componentsMatchedByRegex:regex];

NSLog(@"%@",items);


//需求2:一个网如果需要填写QQ号码(6-11个数字)

NSString *text = @"1231x2455";
NSString *regex = @"^\\d{6,11}$";

// NSArray *items = [text componentsMatchedByRegex:regex];

// NSLog(@"%@",items);

BOOL isMatched = [text isMatchedByRegex:regex];
if(isMatched) {

NSLog(@"是QQ号");

} else {

NSLog(@"不是QQ号");

}




Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐