Objective-C 正则表达式使用,1

学习了一下OC的正则表达式备忘一下

使用正则表达式的步骤:
  • 创建一个一个正则表达式对象:定义规则。
  • 利用正则表达式对象测试,相应的字符串。
    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个能得到匹配
    
  • ? 代表0个或者多个
  • + 至少有一个
  • * 个或多个
  • ^ 以..开头
  • $ 以..结尾
  • 看一个实例
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个匹配

RegexKitLite的基本使用方法

OC自带的正则表达式明显显得过于繁琐,使用RegexKitLite可以很方便得处理匹配结果而且提供一些其他更强大的功能

实例

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));
        }];