简体   繁体   中英

phone number format mask in ios

I'd like a regex or some function to standardize all phone number input from my ios app.

Thus inputs like the following

  • (212)555-5555
  • 2125555555
  • 212-555-5555
  • 212 555 5555
  • 212-5555555

all get translated to

  • (212) 555-5555

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?

^ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM