Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, phone number regex

Tags:

regex

ios

swift

Hopefully a simple one,

I need a a limit of 8 numbers, the user need to write 8 number no more or less.

For now this is my code:

telefonRegex = "^(?=.*[0-9])$"

But it is not working, I just heard about regex fyi.

like image 419
Jonas Larsen Avatar asked Oct 23 '17 22:10

Jonas Larsen


People also ask

What is mobile number validation?

Phone number validation is the process of checking if a phone number is accurate. It lets you find out if the phone number you have for a business contact or customer is active and able to receive calls.

How do I validate an email in swift 5?

Three Methods to Validate Email in SwiftCreating a custom class conforming to RawRepresentable which initializes only if a valid email address is provided. Utilizing Swift's own “specialized regular expression object” to match valid email addresses.


1 Answers

Your current regex never matches a string because it requires to start matching at the start of the string (^), then makes a forward check to require a digit ([0-9]) to appear after any 0+ chars other than line break chars (.*) and then tries to match the end of the string right after the beginning - tha is, it matches an empty string but also requires at least 1 digit in it.

You may just use

let telefonRegex = "^[0-9]{8}$"

or

let telefonRegex = "\\A[0-9]{8}\\z"

to match a string that only consists of 8 digits.

Details

  • ^ - start of string (may be replaced by \\A in the string literal)
  • [0-9]{8} - exactly 8 occurrences of any digit
  • $ - end of string (to make sure the very end of string is matched, use \\z in the string literal).
like image 109
Wiktor Stribiżew Avatar answered Oct 20 '22 10:10

Wiktor Stribiżew