Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 599
UpCat Avatar asked Apr 25 '11 09:04

UpCat


People also ask

How do you check if a string matches a regex?

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.

What can be matched using (*) in a regular expression?

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.

Which command allows you to match a regular expression against a string?

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.

How do you identify a regular expression?

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.


2 Answers

I've used NSPredicate for that purpose:

NSString *someRegexp = ...;  NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", someRegexp];   if ([myTest evaluateWithObject: testString]){ //Matches } 
like image 113
Vladimir Avatar answered Sep 25 '22 16:09

Vladimir


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.

like image 40
Vaz Avatar answered Sep 21 '22 16:09

Vaz