In order to check if a string is a version number thanks to NSRegularExpression
, I created the following pattern:
let pattern = "^(\\\\d+)(?:\\\\.(\\\\d+))?(?:\\\\.(\\\\d+))?(?:\\\\.)?$"
It works pretty well and allows me to match:
"8"
, "12."
, "8.3"
, "8.10."
, "8.2.5"
, "8.2.28."
. However, when I try to improve it with the following pattern, it doesn't work anymore.
let pattern = "^(\\\\d+)(?:\\\\.(\\\\d+)){0,2}(?:\\\\.)?$"
My tests 5 and 6 don't work anymore. Any ideas why?
actually i have tried following things and its working fine. i think issue related you expect the line start with digit and end with matched digit so might be a problem. Here i tried following things.
NSString* aString = @"8 iokdsa da 12. dasdsadaasd 8.3 cccc 8.10. rrr 8.2.5 rrrrr 8.2.28.";
NSRegularExpression* tableRegex = [[NSRegularExpression alloc] initWithPattern:@"(\\d+)(?:\\.(\\d+)){0,2}(?:\\.)?" options:0 error:NULL] ;
[tableRegex enumerateMatchesInString:aString options:0 range:NSMakeRange(0, [aString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSLog(@"Print : %@",[aString substringWithRange:match.range]);
}];
Output :
Print : 8
Print : 12.
Print : 8.3
Print : 8.10.
Print : 8.2.5
Print : 8.2.28.
If you want just end keyword to matched then attached $ signed at end of above expression like as below.
(\\d+)(?:\\.(\\d+)){0,2}(?:\\.)?$
Hope this help you.
Hum... I just figured out what was the problem.
So both patterns match the same whole strings. However the capturing parentheses don't have the same behaviors in both patterns.
If I apply the pattern ^(\\\\d+)(?:\\\\.(\\\\d+))?(?:\\\\.(\\\\d+))?(?:\\\\.)?$
on the string "1.2.3"
, the NSTextCheckingResult
obtained has a numberOfRanges
of 4.
If I apply the pattern ^(\\\\d+)(?:\\\\.(\\\\d+)){0,2}(?:\\\\.)?$
on the string "1.2.3"
, the NSTextCheckingResult
obtained has a numberOfRanges
of 3. It appears that during the second pass into (?:\\\\.(\\\\d+)){0,2}
, a new range isn't created. Instead, the previous range is overwritten.
It explains why my unit tests didn't work anymore. :-)
Thanks to everybody for your answers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.