1

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

Eugene Gordin
  • 4,047
  • 3
  • 47
  • 80

1 Answers1

0

In order to achieve what you want, you I suggest you do one for each case for validation.

Validation

Colons:

^\d{1,2}(?::\d{1,2}){0,2}(?::\d{2})?$

Commas:

^\d{3}(?:,\d{3}){0,2}$

Just the number:

^\d+$

Then assuming you pass validation of each case, use something else for data extraction.

Data Extraction

Colons

Commas:

Just the number:

  • Well, you have what you need here, so no need to make any changes.
Community
  • 1
  • 1
ohaal
  • 5,208
  • 2
  • 34
  • 53
  • Hi! thank you so much! It looks like it's working ;) Do you know by any chance if there is a method in NSRegularExpression that will allow me to get these matched substrings? For example: in 01:34:23 the ones would be 01 34 and 23 ? – Eugene Gordin Mar 04 '13 at 22:30
  • 1
    You would have to modify the regular expression with capture groups in the correct locations. I wouldn't recommend the "One ring to rule them all" solution if you do this. If you add this specification to your question, I'll edit my answer accordingly. – ohaal Mar 04 '13 at 22:35
  • thank you! just edited the question a bit! I also added one more valid/invalid case, but I guess it can be fixed by adding {1,2} after \d ?! – Eugene Gordin Mar 04 '13 at 22:48