this might be a dumb question but I'm new to iOS programming and I just couldn't think of anything. for my app I need to check if a certain postal code is in a range. It's easy to do for German or US codes which are plain numbers, but now I have to do it for canadian.
Example canadian postal code looks like this: A0A, J3X, R7N, V1M.
Is there a way to do this?
Thanks for any help!
You can use a regex like this:
^(A0A|J3X|R7N|V1M)$
If you want ranges you can do something like this:
^(A0A|J3X|R7N|V1[M-Z])$
^--- Will match V1M until V1Z
Another example for range V1Z could be:
^(A0A|J3X|R7N|V[5-9][M-Z])$
^--- Will match VxM until VxZ and V5x until V9x
If you just want a digit you can use \d
(it's the shortcut for [0-9]
). Same for \w
that means [A-Za-z0-9_]
.
You can specify ranges using regex classes. Like:
[0-4]
[7-9]
[A-M]
[O-X]
This answer on SO has a good description of how regular expression character class ranges work. To paraphrase: you aren't just limited to letters and numbers ([A-Z]
or [0-9]
), but you should be careful attempting any more complicated ranges.
A range will allow for any character between, according to the list of ASCII characters, the start and end characters to match. This means any range is technically valid (you may just see odd results). For example, these two classes are the same:
[0-Z]
[0-9:;<=>?@A-Z]