iphone正則表達式的簡單使用

字號:


    在 4.0 之后,系統(tǒng)就有了它自己的類(NSRegularExpression,NSRegularExpression)來使用正則表達式,,之前都是要添加第三方類庫 RegexKitLite 來使用
    這兩個類的簡單使用:
    NSString *str = @"3sdfh*odsi";
    //匹配第一個字符是數(shù)字
    NSRegularExpression *regex1 = [NSRegularExpression regularExpressionWithPattern:@"bd.*" options:0 error:nil];
    if (regex1 != nil) {
    NSTextCheckingResult *result1 = [regex1 firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    if (result1) {
    NSLog(@"第一個是數(shù)字");
    }else{
    NSLog(@"第一個不是數(shù)字");
    }
    }
    //匹配特殊字符 W (W是大寫)匹配任意不是字母,數(shù)字,下劃線,漢字的字符
    NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:@".*W.*" options:0 error:nil];
    if (regex2) {
    NSTextCheckingResult *result2 = [regex2 firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    if (result2) {
    NSLog(@"有特殊字符");
    }else{
    NSLog(@"沒有特殊字符");
    }
    }