Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phone number Regex not working with swift [duplicate]

Tags:

regex

swift

I'm developing an app which works with phone numbers, but I'm having a problem using regex to find the phonenumber in a string.

My app looks through the contact's phone number which can be:

(with dash "-")
XXXX-XXXX
XXXXX-XXXXX
(YY) XXXX-XXXX
(YY) XXXXX-XXXX
+ZZ (YY) XXXX-XXXX
+ZZ (YY) XXXXX-XXXX


(without dash)
XXXXXXXX
XXXXXXXXX
(YY) XXXXXXXX
(YY) XXXXXXXXX
+ZZ (YY) XXXXXXXX
+ZZ (YY) XXXXXXXXX

Based on all this possibilities above, I've written the following code:

    let range = telefone.rangeOfString("[0-9]{4,5}-[0-9]{4}", options:.RegularExpressionSearch)
    let range2 = telefone.rangeOfString("[0-9]{9}$", options:.RegularExpressionSearch)

    var found: String?

    if range != nil{
        found = telefone.substringWithRange(range!)
    }else if range2 != nil{
        found = telefone.substringWithRange(range2!)
    }

    print(found)

range is the regex to find phoneNumbers (with dash "-")
range2 is the regex to fund phone numbers (without dash)

With this code I get only the phone number, without the country code or the area code.

The problem is, this code returns nil on found variable when I test with a phone number like
+ZZ (YY) XXXXX-XXXX

Can someone help me find another way to write a regex to get only the "X" values of the string containing all the contact phone number?

UPDATE:

I noticed the code above, the variable range, returns null

    var telefone = "+42 43 23123-2221"

    let range = telefone.rangeOfString("\\d{4,5}\\-?\\d{4}", options:.RegularExpressionSearch)

    print("range \(range)")   //here returns nil

playground

like image 361
marchiore Avatar asked Dec 06 '15 17:12

marchiore


People also ask

How do I validate a phone number?

Mobile Number validation criteria:The first digit should contain numbers between 6 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.


2 Answers

This may be not the most pleasant-looking regex but I believe it does the job.

(\+\d{2}\s*(\(\d{2}\))|(\(\d{2}\)))?\s*\d{4,5}\-?\d{4}

enter image description here

Demo: https://regex101.com/r/gM4uT3/3

Edit:

If I understood you correctly, this would only match the phone number without any area code etc (Just the Xs) inside a capturing group.

(?:\+\d{2}\s*(?:\(\d{2}\))|(?:\(\d{2}\)))?\s*(\d{4,5}\-?\d{4})

enter image description here

Demo: https://regex101.com/r/gM4uT3/6

like image 85
Amen Jlili Avatar answered Oct 24 '22 16:10

Amen Jlili


If the brackets are option ie. "+42 (43) 23123-2221" or "+42 43 23123-2221":

(?:(\+\d\d\s+)?((?:\(\d\d\)|\d\d)\s+)?)(\d{4,5}\-?\d{4})

Regular expression visualization

Alternatively if brackets are required:

(?:(\+\d\d\s+)?(\(\d\d\)\s+)?)(\d{4,5}\-?\d{4})

Regular expression visualization

You might want to replace \s+ with simply a single space depending on your spacing requirements.

Also note you might want to add anchors ^ to the beginning and $ and to the end to ensure complete match of string.

https://regex101.com/r/bR5uM3/2

http://swiftstub.com/44951173

var telefone = "+42 43 23123-2221"

// Use this regular expression to require "+42 (43) 23123-2221" brackets
//let phoneNumberRegEx = "(?:(\\+\\d\\d\\s+)?(\\(\\d\\d\\)\\s+)?)(\\d{4,5}\\-?\\d{4})";


// Use this regular expression to make them optional "+42 43 23123-2221" brackets
let phoneNumberRegEx = "(?:(\\+\\d\\d\\s+)?((?:\\(\\d\\d\\)|\\d\\d)\\s+)?)(\\d{4,5}\\-?\\d{4})";

let range = telefone.rangeOfString(phoneNumberRegEx, 
    options:.RegularExpressionSearch)

print("range \(range)")

var found = telefone.substringWithRange(range!)

print(found)



let regex = try! NSRegularExpression(pattern: phoneNumberRegEx, options: [])

let telephoneRange = NSMakeRange(0, telefone.characters.count)
let result = regex.firstMatchInString(telefone, options: NSMatchingOptions(rawValue: 0), range: telephoneRange)
let r1 = result!.rangeAtIndex(1)
let r2 = result!.rangeAtIndex(2)
let r3 = result!.rangeAtIndex(3)
if (r1.length > 0) {
    let phoneCountry = (telefone as NSString).substringWithRange(r1)
    print("country: \(phoneCountry)")
}
if (r2.length > 0) {
    let phoneArea = (telefone as NSString).substringWithRange(r2)
    print("area: \(phoneArea)")
}
if (r3.length > 0) {
    let phone = (telefone as NSString).substringWithRange(r3)
    print("phone: \(phone)")
}

This returns the following result:

range Optional(Range(0..<17))
+42 43 23123-2221
country: +42
area: 43
phone: 23123-2221
like image 21
Dean Taylor Avatar answered Oct 24 '22 17:10

Dean Taylor