Reputation: 3850
I am trying to execute the following regex: ^(\$.)([\d]{1,10})?
The result for the $C14325
string at https://regex101.com is [0-2]:"$C"
and [2-7]:"14325"
.
But, when I the following code is executed using NSRegularExpression
, then it returns as single matching item, rather than a group.
Basically, I am trying to group those results and finding a way what result corresponds to which regex.
NSString *regexStr=@"^(\\$.)([\\d]{1,10})?";
NSString *inputStr=@"$C14325";
NSError *regexError;
NSRegularExpression *aRegx=[NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:®exError];
NSArray *results=[aRegx matchesInString:inputStr options:0 range:NSMakeRange(0, inputStr.length)];
There was answer at Named capture groups with NSRegularExpression , but I think rangeAtIndex
will throw exception if its not able to find the value.
Upvotes: 3
Views: 2025
Reputation: 726479
You've got the regex part right. All you need to do is iterating matches inside the results
:
for (NSTextCheckingResult *match in results) {
NSRange matchRange = [match range];
NSRange first = [match rangeAtIndex:1];
NSRange second = [match rangeAtIndex:2];
NSLog(@"1:%@ 2:%@.", [NSValue valueWithRange:first], [NSValue valueWithRange:second]);
}
1:NSRange: {0, 2} 2:NSRange: {2, 5}.
Upvotes: 5