I have an array of data from which I would like to extract rows containing numbers and numbers only. Examples on rows:
15, +2, ‘ ‘, 7, 9, +21
(The ‘ ‘ represents one or more whitespaces).
In this case I would like to extract only 15, 7 and 9. I use a predicate in the following way:
NSString *pattern = @"[^0-9]";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if (![predicate evaluateWithObject:myStringToMatch])
// Extract ...
I have tested my pattern using an online regex tester and found that [^0-9] does match anything but the numbers 0-9. However when I run the above code it only matches the whitespaces and not the eg +2, which I am pretty sure that it should do. Just to clarify, myStringToMatch is an NSString object.
I have no clue why it doesn’t match my pattern. Can anyone give me a hint on what I’m doing wrong?
Thanks.
You regex matches anything but a single digit. If you are going to match rows containing numbers and numbers only, you need a regex which will not match on rows containing non-numbers.
You can use the following regex:
^[0-9]+$. It matches one ore more (+) digits ([0-9]) in a row and nothing else (anchors^and$ensure that).Then, instead of filtering rows that don’t match, you process only the rows that do: