代码:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { // 待判定的字符串 NSString *str = @"Hello World"; // 正则表达式字符串 NSString *regex = @"^[a-zA-Z ]+$"; // 谓词 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; // 谓词求值 BOOL isValid = [predicate evaluateWithObject:str]; NSLog(@"%@", isValid ? @"YES" : @"NO"); } return 0; }
输出:
YES