iOS谓词匹配字符串以及替换

1.判断某个字符串是否符合某个正则表达式,通常用这个方法:

// 判断字符串首字符是否为字母
NSString *string = @"wo";
// 1、准备正则式
NSString *regex = @"^[A-Za-z]*$"; // 只能是字母,不区分大小写
// 2、拼接谓词
NSPredicate *predicateRe1 = [NSPredicate predicateWithFormat:@"self matches %@", regex];
// 3、匹配字符串
BOOL resualt = [predicateRe1 evaluateWithObject:string];
NSLog(@"匹配结果%d", resualt);

2.但是我们开发过程中也有可能遇到这种需求,匹配字符串并且找出符合正则的字符,并替换成其他的字符显示出来,这种情况下可以用这个方法:

NSString *string = textField.text;

 // 1、准备正则式

    NSString *regex = @"[^\x00-\xff]|[{}()/]";

    

    NSString * replacement = @"";

    //    // 创建 NSRegularExpression 对象,匹配 正则表达式

    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:regex

                                                                       options:NSRegularExpressionCaseInsensitive

                                                                         error:nil];

    NSString *resultStr = string;

    // 替换匹配的字符串为 searchStr

    resultStr = [regExp stringByReplacingMatchesInString:string

                                                 options:NSMatchingReportProgress

                                                   range:NSMakeRange(0, string.length)

                                            withTemplate:replacement];

    NSLog(@"\nsearchStr = %@\nresultStr = %@",string,resultStr);

    textField.text = resultStr;

原文地址:https://www.cnblogs.com/cui-cui/p/7512846.html