![]() matches() returns the boolean value true if this string matches with the regular expression, else it returns false. matches() method and pass regular expression as argument. Validate Phone Number using Regular Expression We use String. How do you check if a string is a phone number? Then follows 2 digits indicating to which Mobile Operator’s pool the number originally belonged when it was taken into usage. The first digit of the “zone prefix” of a mobile number is always ‘4’. ![]() ![]() Mobile phone numbers always consist of 10 digits. Since you'd need a regex anyway, you might as well have the regex do all the work.^(?:(?:\ |0 matches (123)456-7890 or (123)4567890. Take, for instance, my test script that downloads a web page and extracts all phone numbers using the regex. Unless you are certain that you are always going to be accepting numbers from one locale, and they are always going to be in one format, I would heavily suggest not writing your own code for this, and using libphonenumber for validating and displaying phone numbers.Īlthough the answer to strip all whitespace is neat, it doesn't really solve the problem that's posed, which is to find a regex. Google's version has code for Java and Javascript, but people have also implemented libraries for other languages that use the Google i18n phone number dataset: ![]() Libphonenumber also gives you many additional benefits, such as grabbing the location that the phone number is detected as being, and also getting the time zone information from the phone number: PhoneNumberOfflineGeocoder Resultsīut the invalid Australian phone number ( (09) 9999 9999) returns that it is not a valid phone number. Out-of-country format from CH 00 61 2 9999 9999 So not only do you learn if the phone number is valid (which it is), but you also get consistent phone number formatting in your locale.Īs a bonus, libphonenumber has a number of datasets to check the validity of phone numbers, as well, so checking a number such as 61299999999 (the international version of (02) 9999 9999) returns as a valid number with formatting: Validation Results Out-of-country format from CH 00 1 23 ext. Using one of your more complex examples, 1-23 x1234, you get the following data out of libphonenumber (link to online demo): Validation Results I would suggest skipping a simple regular expression to test your phone number against, and using a library such as Google's libphonenumber (link to GitHub project).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |