Reputation: 47861
I'd like a regex or some function to standardize all phone number input from my ios app.
Thus inputs like the following
all get translated to
would this following regex work to match the phone numbers into 3 match groups which I can then format into the correct output string?
^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$
Is the $ sign at the end of the regex required or does that mess things up?
Is regex the best way to do this in iOS?
Upvotes: 0
Views: 723
Reputation: 17958
^
and $
in a regex match the beginning and end of a line of input. You have not provided enough information to determine if these anchors are appropriate in this particular case.
Since you're working in iOS have you looked at the NSDataDetector
class? It provides mechanisms for detecting strings which could be valid phone numbers in many different formats. This would give you phone number detection matching the behavior users see in many of the other apps on their devices.
NSDataDetector
does not provide a mechanism for re-formatting phone numbers so you would still need to determine how you want to reformat strings detected as possible phone numbers (which may contain more or less than 10 digits). If you do so you should probably fall back to preserving the original format of any detected number which does not match one of your expected formats.
Upvotes: 1