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

前端 未结 4 868
庸人自扰
庸人自扰 2021-01-30 21:56

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

4条回答
  •  耶瑟儿~
    2021-01-30 22:25

    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.

提交回复
热议问题