zoukankan      html  css  js  c++  java
  • iOS开发中正则式的使用

    iOS开发中正则式的使用

    第一:常规的使用方式

    NSString *str = @"abcded111093212qweqw";
    
    //找到内部一个即可
    NSString *pattern = @"\d{5,11}";//判断是不是QQ
    // | 匹配多个条件,相当于or或
    
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    // 2.测试字符串
    NSArray *results = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    
    // 3.遍历结果
    for (NSTextCheckingResult *result in results) {
        NSLog(@"%@ %@", NSStringFromRange(result.range), [str substringWithRange:result.range]);
    }
    

    第二:使用第三方库RegexKitLite:

    RegexKitLite是MRC的

    1. 需 在Compile Sources中添加 -fno-objc-arc编译参数,以便在ARC项目下使用
    2. 需在Link Binary With Libraries中添加依赖库:libicucore.dylib

    使用

    //2.1:简单使用
    NSString *str = @"abcded111093212qweqw";
    NSString *pattern = @"\d{5,11}";//判断是不是QQ
    // 数组中装的就是匹配的结果
    NSArray *cmps = [str componentsMatchedByRegex:pattern];
    
     //2.1:高级使用
     NSString *str = @"abcded111093212qweqw";
    NSString *pattern = @"\d{5,11}";//判断是不是QQ
     [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));
        }];
  • 相关阅读:
    HDU-1205
    HDU-2033
    HDU-2032
    HDU-2031
    HDU-2030
    HDU-2029
    HDU-2028
    HDU-2027
    HDU-2026
    HDU-2025
  • 原文地址:https://www.cnblogs.com/fengtengfei/p/4925983.html
Copyright © 2011-2022 走看看