标签:
NSString *userName = @"12132321";
NSString *pattern = @"\\d"匹配数字
NSString *pattern = @"[a-zA-Z]";
NSString *pattern = @"[[0-9][0-9]]"; 匹配两个数字
NSString *pattern = @"\\d\\d"; 匹配两个数字
NSString *pattern = @"\\d{2, 4}"; 匹配连续的数字2个到4个能得到匹配
NSString *userName = @"121323232"; //要匹配的字符串 NSString *pattern = @"\\d"; //匹配规则 NSRegularExpression *regex = [[NSRegularExpression alloc] initwithPattern:pattern optons:0 error:nil]; //测试字符串 NSArray *results = [regex matchesInString:userName options:0 range:NSMakeRange(0, userName.length)];]; NSLog(@"%zd", results.count);
results 存储的匹配的所有结果,运行上述程序,输出9 明显得到9个匹配
实例
NSString *str = @"#呵呵呵#[偷笑] http://foo.com/blah_blah #解放军#//http://foo.com/blah_blah @Ring花椰菜:就#范德萨发生的#舍不得打[test] 就惯#急急急#着他吧[挖鼻屎]//@崔西狮:小拳头举起又放下了 说点啥好呢…… //@toto97:@崔西狮 蹦米咋不揍他#哈哈哈# http://foo.com/blah_blah"; NSString *emotionPattern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]" 匹配表情比如 [哈哈] \\匹配URl NSString *urlPattern = @"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))"; \\多个条件可以使用或运算|| 联合匹配 NSString *pattern = [NSString stringWithFormat:@"%@|%@|%@|%@", emotionPattern, urlPattern]; \\使用RegexKitLite方法 \\遍历所有匹配结果 [str enumerateStringsMatchedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) { NSLog(@"%@ %@", *capturedStrings, NSStringFromRange(*capturedRanges)); }]; \\以正则表达式为分隔符 [str enumerateStringsSeparatedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) { NSLog(@"%@ %@", *capturedStrings, NSStringFromRange(*capturedRanges)); }];
标签:
原文地址:http://www.cnblogs.com/code-changeworld/p/4713218.html