Reputation: 419
I have declare a NSRegularExpression
. For example like [0-9]{1,4}|abc|ABC
. And I input a NSString: @"123"
. If I check the NSTextCheckingResult
, it is not nil. So I know the string match the Regex. However, can I know more about which part is matched? For this scenario, I know Regex [0-9]{1,4}
is matched. How can I do this? Thanks!
Upvotes: 0
Views: 129
Reputation: 539685
If I understand your question correctly, you have to use
capture groups (...)
:
NSString *pattern = @"([0-9]{1,4})|(abc)|(ABC)";
If the string matches the first capture group in the pattern then
[result rangeAtIndex:1]
will be the range of matching substring, while
[result rangeAtIndex:2]
[result rangeAtIndex:3]
have range.location == NSNotFound
. Example:
NSString *pattern = @"([0-9]{1,4})|(abc)|(ABC)";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSString *str = @"123";
NSTextCheckingResult *result = [regex firstMatchInString:str options:0 range:NSMakeRange(0, str.length)];
NSLog(@"%@", NSStringFromRange([result rangeAtIndex:1])); // {0, 3}
NSLog(@"%@", NSStringFromRange([result rangeAtIndex:2])); // {9223372036854775807, 0}
NSLog(@"%@", NSStringFromRange([result rangeAtIndex:3])); // {9223372036854775807, 0}
Upvotes: 2
Reputation: 285069
Press ⇧⌘0 and type NSTextCheckingResult
or ⌥-click on the symbol to get the class definition.
There are properties range
, resultType
, numberOfRanges
and many more.
Or call rangeOfFirstMatchInString:options:range
on the NSRegularExpression
instance to get the range directly.
Upvotes: 0