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?
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
You can repeat expressions with an asterisk or plus sign. A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
The regexp command is similar to the string match command in that it matches an exp against a string. It is different in that it can match a portion of a string, instead of the entire string, and will place the characters matched into the matchVar variable.
A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With