How to build regex for complex Indonesian phone number format?

7.7k views Asked by At

Recently, i am using regexpal to build this custom regex. I am working with several test case for Indonesian phone number.

Here an example for the simple one 08xx-3456-7890 or 08xx34567890

but it can be a bit confusing if i get this following format

here is my phone (08xx)34567890
08xx.3456.7890
08xx 3456 7890
(+62) 8xx34567890
(+62) 8xx-3456-7890
+628xx34567890
+62-8xx-3456-7890
+628xx 3456 7890

here is regex i have done with (08|628|62)[\s\)\-]*(\s|(\d){3,}) but i can not cover all of those sample.

+62 is country code

Can you please help me with any solution to validate those format?

the phone number is possible contains string instead just number, because it is part of sentence

3

There are 3 answers

1
Nicolas On

You can try to remove tokens first with regex [().- ] and replace with empty string. Then you can use (?:\+62)?0?8\d{2}(\d{8}) to match a phone number. This matches an optional +62, an optional 0, 8, two digits (xx) and the phone number: 8 digits. Group 1 contains the phone number.

0
Saurabh Sharma On

// MARK: - Validate Indonesia Mobile Number Without Country Code //The number should be start by 8 digit character

class func validateMobileNumber(_ number: String) -> Bool {
    let numberRegEx = "[8][0-9]{10,14}"
    let numberTest = NSPredicate(format: "SELF MATCHES %@", numberRegEx)
    if numberTest.evaluate(with: number) == true {
        return true
    }
    else {
        return false
    }
}
4
Syakur Rahman On

For Indonesian phone numbers, this roughly should work.

(\()?(\+62|62|0)(\d{2,3})?\)?[ .-]?\d{2,4}[ .-]?\d{2,4}[ .-]?\d{2,4}

To see it in action: https://regex101.com/r/qtEg6H/3

Also see the answer in the comment below for a more efficient way.