Reputation: 9586
I would like to know whether or not a certain string has a regex.
I wrote the code below which in order to match strings similar to the following:
"A|3|a3\n"
However the code below gets an array of matches. I do not want that as I want to simply understand whether or not my response string matches the criteria given by the regex. Any suggestion on how to do so?
NSString * response = "A|3|a3\n";
NSRange searchedRange = NSMakeRange(0, [ response length]);
NSString *pattern = @"[ABC]\|[0-9]\|[a][0-9]$";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:response options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches){
NSString* matchText = [response substringWithRange:[match range]];
NSLog(@"match: %@", matchText);
}
Upvotes: 0
Views: 58
Reputation: 626738
I think you are looking for a kind of an IsMatch()
function. Here is an example:
NSRange matchRange = [regex rangeOfFirstMatchInString:response options:NSMatchingReportProgress range:searchedRange];
BOOL isFound = NO;
// Did we find a matching range
if (matchRange.location != NSNotFound)
isFound = YES;
Upvotes: 0
Reputation: 26026
Xcode should throw an warning:
Warning: Unknown escape sequence '\|'
for this line:
NSString *pattern = @"[ABC]\|[0-9]\|[a][0-9]$";
"\" escape indeed the next character (to some special signification, like the classical "\n"), but "\|" is a unknown escape sequence for a normal string. So you have to "double it":
NSString *pattern = @"[ABC]\\|[0-9]\\|[a][0-9]$"
Upvotes: 1