just faced the problem of inability to write a good regex that would satisfy my needs. I've never used regex before, so that wasn't a big surprise for me.
Here are the good input examples that I'm trying to validate:
- 01
- 00:01
- 01:02:03
- 01:02:03:04 - max 3 colons possible
- 123,456,789 - max two commas possible
- 40000035
- 1:2:06
here are the bad ones:
- ,3234
- 134,2343,333
- 000:01:00
- :01:03:00
- :01
- 01:
First I tried to write one that would cover at least all the colon cases and here is what I have:
NSUInteger numberOfMatches = -1;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([([0-9]{1,2}):]{1,3})([0-9]{1,2})"
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
NSLog(@"error %@", error);
}
numberOfMatches = [regex numberOfMatchesInString:stringToValidate
options:0
range:NSMakeRange(0, [stringToValidate length])];
I'm also curious if NSRegularExpression has any methods to extract the validated substrings in a some sort of an array?!
For example:
12:23:63 --- would be validated and the array would contain [12,23,63]
234 --- would be validated and the array would contain [234]
123,235,653 --- would be validated and the array would contain [123235653]
basically colon separated input would be as separate values and everything else would be as one value