How to check if string matches a regular expression in objective-c?

你说的曾经没有我的故事 提交于 2019-12-02 17:41:15

I've used NSPredicate for that purpose:

NSString *someRegexp = ...; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", someRegexp]; 

if ([myTest evaluateWithObject: testString]){
//Matches
}

Another way to do this, which is a bit simpler than using NSPredicate, is an almost undocumented option to NSString's -rangeOfString:options::

NSRange range = [string rangeOfString:@"^\\w+$" options:NSRegularExpressionSearch];
BOOL matches = range.location != NSNotFound;

I say "almost undocumented", because the method itself doesn't list the option as available, but if you happen upon the documentation for the Search and Comparison operators and find NSRegularExpressionSearch you'll see that it's a valid option for the -rangeOfString... methods since OS X 10.7 and iOS 3.2.

Use the -isMatchedByRegex: method.

if([someString isMatchedByRegex:@"^[0-9a-fA-F]+:"] == YES) { NSLog(@"Matched!\n"); }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!