开发者

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

开发者 https://www.devze.com 2023-02-28 18:19 出处:网络
since regular exressions are not supported in Cocoa I find RegexKitLite very usefull. But all examples extract matching strings.

since regular exressions are not supported in Cocoa I find RegexKitLite very usefull. But all examples extract matching strings.

开发者_开发技巧I just want to test if a string matches a regular expression and get a Yes or No.

How can I do that?


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: method:

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.


NSRegularExpression is another option:

http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html


Use the -isMatchedByRegex: method.

if([someString isMatchedByRegex:@"^[0-9a-fA-F]+:"] == YES) { NSLog(@"Matched!\n"); }
0

精彩评论

暂无评论...
验证码 换一张
取 消