In the following code I am trying to get the output to be the different formatting of phone numbers and if it is either valid or not. I figured everything out but the Java Regular Expression code on line 11 the string pattern.
import java.util.regex.*;
public class MatchPhoneNumbers {
public static void main(String[] args) {
String[] testStrings = {
/* Following are valid phone number examples */
"(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
/* Following are invalid phone numbers */
"(1234567890)","123)4567890", "12345678901", "(1)234567890",
"(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};
// TODO: Modify the following line. Use your regular expression here
String pattern = "^/d(?:-/d{3}){3}/d$";
// current pattern recognizes any string of digits
// Apply regular expression to each test string
for(String inputString : testStrings) {
System.out.print(inputString + ": ");
if (inputString.matches(pattern)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
}
asked Feb 8, 2017 at 4:11
5
Basically, you need to take 3 or 4 different patterns and combine them with «|»:
String pattern = "\d{10}|(?:\d{3}-){2}\d{4}|\(\d{3}\)\d{3}-?\d{4}";
d{10}
matches 1234567890(?:d{3}-){2}d{4}
matches 123-456-7890(d{3})d{3}-?d{4}
matches (123)456-7890 or (123)4567890
answered Feb 8, 2017 at 5:07
Patrick ParkerPatrick Parker
4,8133 gold badges19 silver badges50 bronze badges
3
international phone number regex
String str= "^\s?((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?\s?";
if (Pattern.compile(str).matcher(" +33 - 123 456 789 ").matches()) {
System.out.println("yes");
} else {
System.out.println("no");
}
answered Jan 4, 2019 at 18:17
1
Considering these facts about phone number format:-
- Country Code prefix starts with ‘+’ and has 1 to 3 digits
- Last part of the number, also known as subscriber number is 4 digits in all of the numbers
- Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
String allCountryRegex = "^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$";
Let’s break the regex and understand,
^
start of expression(\+\d{1,3}( )?)?
is optional match of country code between 1 to 3 digits prefixed with ‘+’ symbol, followed by space or no space.((\(\d{1,3}\))|\d{1,3}
is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.\d{3,4}[- .]?
is mandatory group of 3 or 4 digits followed by hyphen, space or no space\d{4}
is mandatory group of last 4 digits$
end of expression
This regex pattern matches most of the countries phone number format including these:-
String Afghanistan = "+93 30 539-0605";
String Australia = "+61 2 1255-3456";
String China = "+86 (20) 1255-3456";
String Germany = "+49 351 125-3456";
String India = "+91 9876543210";
String Indonesia = "+62 21 6539-0605";
String Iran = "+98 (515) 539-0605";
String Italy = "+39 06 5398-0605";
String NewZealand = "+64 3 539-0605";
String Philippines = "+63 35 539-0605";
String Singapore = "+65 6396 0605";
String Thailand = "+66 2 123 4567";
String UK = "+44 141 222-3344";
String USA = "+1 (212) 555-3456";
String Vietnam = "+84 35 539-0605";
Source:https://codingnconcepts.com/java/java-regex-for-phone-number/
answered May 27, 2020 at 12:59
The regex that you need is:
String regEx = "^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$";
Regex explanation:
^\(?
— May start with an option «(«
(\d{3})
— Followed by 3 digits
\)?
— May have an optional «)»
[- ]?
— May have an optional «-» after the first 3 digits or after optional ) character
(\d{3})
— Followed by 3 digits.
[- ]?
— May have another optional «-» after numeric digits
(\d{4})$
— ends with four digits
answered Feb 8, 2017 at 4:34
1
Create a non-capturing group for three digits in parenthesis or three digits (with an optional dash). Then you need three digits (with another optional dash), followed by four digits. Like, (?:\(\d{3}\)|\d{3}[-]*)\d{3}[-]*\d{4}
. And you might use a Pattern
. All together like,
String[] testStrings = {
/* Following are valid phone number examples */
"(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
/* Following are invalid phone numbers */
"(1234567890)","123)4567890", "12345678901", "(1)234567890",
"(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};
Pattern p = Pattern.compile("(?:\(\d{3}\)|\d{3}[-]*)\d{3}[-]*\d{4}");
for (String str : testStrings) {
if (p.matcher(str).matches()) {
System.out.printf("%s is valid%n", str);
} else {
System.out.printf("%s is not valid%n", str);
}
}
answered Feb 8, 2017 at 4:31
Elliott FrischElliott Frisch
196k20 gold badges157 silver badges246 bronze badges
1
In this article, we’ll learn how to validate mobile phone number of different country’s format using Java Regex (Regular Expressions)
Phone Number Format
A typical mobile phone number has following component:
+<country_code> <area_code> <subscriber_number>
Where depending on the country,
- country_code is somewhere between 1 to 3 digits
- area_code and subscriber_number combined is somewhere between 8 to 11 digits
If you simply require a regex to match all country format then here it is,
"^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$"
If you want to know **how we came up with this regex?** then please read this full article.
1. Regex to match 10 digit Phone Number with No space
This is simplest regex to match just 10 digits. We will also see here how to use regex to validate pattern:
String regex = "^\d{10}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("9876543210");
matcher.matches(); // returns true if pattern matches, else returns false
Let’s break the regex and understand,
^
start of expressiond{10}
is mandatory match of 10 digits without any space$
end of expression
You can make regex more flexible to match between 8 to 11 digits phone number with no space, using this regex:
String noSpaceRegex = "^\d{8,11}$";
2. Regex to match 10 digit Phone Number with WhiteSpaces, Hyphens or No space
String spacesAndHyphenRegex = "^(\d{3}[- ]?){2}\d{4}$";
Let’s break the regex and understand,
^
start of expressiond{3}
is mandatory match of 3 digits[- ]?
is optional match of whitespace or hyphen after 3 digits{2}
is to repeat the above matchd{3}[- ]?
two times becomes total 6 digitsd{4}
is mandatory match of last 4 digits$
end of expression
This Pattern will match mobile phone numbers like 9876543210, 987 654 3210, 987-654-3210, 987 654-3210, 987 6543210, etc.
3. Regex to match 10 digit Phone Number with Parentheses
String parenthesesRegex = "^((\(\d{3}\))|\d{3})[- ]?\d{3}[- ]?\d{4}$";
Let’s break the regex and understand,
^
start of expression(\(\d{3}\))|\d{3})
is mandatory match of 3 digits with or without parentheses[- ]?
is optional match of whitespace or hyphen after after 3 digits\d{3}[- ]?
is mandatory match of next 3 digits followed by whitespace, hyphen or no space\d{4}
is mandatory match of last 4 digits$
end of expression
This Pattern will match mobile phone numbers with spaces and hyphen, as well as numbers like (987)6543210, (987) 654-3210, (987)-654-3210 etc.
4. Regex to match 10 digit Phone number with Country Code Prefix
This regex is combined with regex to include parenthesis
String countryCodeRegex = "^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$";
Let’s break the regex and understand,
^
start of expression(\+\d{1,3}( )?)?
is optional match of country code between 1 to 3 digits prefixed with + symbol, followed by space or no space.((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}
is mandatory match of 10 digits with or without parenthesis, followed by whitespace, hyphen or no space$
end of expression
This Pattern will match mobile phone numbers from previous examples as well as numbers like +91 (987)6543210, +111 (987) 654-3210, +66 (987)-654-3210 etc.
5. Regex to match Phone Number of All Country Formats
Before we start defining a regex, let’s look at some of the country phone number formats:-
Abkhazia +995 442 123456
Afghanistan +93 30 539-0605
Australia +61 2 1255-3456
China +86 (20) 1255-3456
Germany +49 351 125-3456
Indonesia +62 21 6539-0605
Iran +98 (515) 539-0605
Italy +39 06 5398-0605
New Zealand +64 3 539-0605
Philippines +63 35 539-0605
Singapore +65 6396 0605
Thailand +66 2 123 4567
UK +44 141 222-3344
USA +1 (212) 555-3456
Vietnam +84 35 539-0605
Let’s extract some information from these numbers:-
- Country Code prefix starts with ‘+’ and has 1 to 3 digits
- Last part of the number, also known as subscriber number is 4 digits in all of the numbers
- Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
Let’s see again on regex from previous example to validate country code:
String countryCodeRegex = "^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$"l
The above regex is to match 10 digit phone numbers, Let’s make some changes in this and make it more flexible to match 8 to 11 digits phone numbers:-
Regex to Match All Country Formats
String allCountryRegex = "^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$";
Let’s break the regex and understand,
^
start of expression(\+\d{1,3}( )?)?
is optional match of country code between 1 to 3 digits prefixed with ‘+’ symbol, followed by space or no space.((\(\d{1,3}\))|\d{1,3}
is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.\d{3,4}[- .]?
is mandatory group of 3 or 4 digits followed by hyphen, space or no space\d{4}
is mandatory group of last 4 digits$
end of expression
6. Regex to match Phone Number of Specific Country Format
As you saw in the previous example that we have to add some flexibility in our regex to match all countries’ formats. If you want more strict validation of specific country format then here are examples of India and Singapore Phone number regex pattern:
String indiaRegex = "^(\+\d{2}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$";
String singaporeRegex = "^(\+\d{2}( )?)?\d{4}[- .]?\d{4}$";
В этом уроке мы рассмотрим, как проверить номер телефона в Java с помощью регулярных выражений (RegEx).
Телефонные номера трудно проверить. Разные страны имеют разные форматы, а некоторые страны даже используют несколько форматов и кодов стран.
Чтобы проверить номер телефона с помощью регулярных выражений, вам придется написать пару утверждений.
Эти утверждения зависят от вашего проекта, его локализации и стран, в которых вы хотите его применить.
Для стандартной проверки номера телефона в США мы можем использовать длинное, довольно надежное выражение:
^(+d{1,2}s)?(?d{3})?[s.-]?d{3}[s.-]?d{4}$
4 группы в выражении соответствуют коду страны, номеру региона, номеру абонента и добавочному номеру.
123-456-7890
(123) 456-7890
etc...
Вы можете написать другое выражение, введя набор правил для групп (в зависимости от страны) и форматов.
Pattern simplePattern = Pattern.compile("^\+\d{10,12}$");
Pattern robustPattern = Pattern.compile("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$");
String phoneNumber = "+12 345 678 9012";
Matcher simpleMatcher = simplePattern.matcher(phoneNumber);
Matcher robustMatcher = robustPattern.matcher(phoneNumber);
if (simpleMatcher.matches()) {
System.out.println(String.format("Simple Pattern matched for string: %s", phoneNumber));
}
if(robustMatcher.matches()) {
System.out.println(String.format("Robust Pattern matched for string: %s", phoneNumber));
}
Robust Pattern matched for string: +12 345 678 9012
Совпадения здесь могли бы соответствовать нескольким форматам:
Pattern robustPattern = Pattern.compile("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$");
List<String> phoneNumbers = List.of(
"+12 345 678 9012",
"+123456789012",
"345.678.9012",
"345 678 9012"
);
for (String number : phoneNumbers) {
Matcher matcher = robustPattern.matcher(number);
if(matcher.matches()) {
System.out.println(String.format("Robust Pattern matched for string: %s", number));
}
}
Результат:
Robust Pattern matched for string: +12 345 678 9012
Robust Pattern matched for string: 345.678.9012
Robust Pattern matched for string: 345 678 9012
Объединяем несколько регулярных выражений
Вместо единого универсального надежного регулярного выражения, охватывающего все крайние случаи, страны и т.д., вы можете выбрать несколько различных шаблонов, которые будут охватывать входящие телефонные номера. Чтобы упростить задачу – вы можете связать эти выражения с помощью оператора | , чтобы проверить, соответствует ли номер телефона какому-либо из шаблонов:
Pattern robustPattern = Pattern
.compile(
// Robust expression from before
"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$"
// Area code, within or without parentheses,
// followed by groups of 3-4 numbers with or without hyphens
+ "| ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
// (+) followed by 10-12 numbers
+ "|^\+\d{10,12}"
);
List<String> phoneNumbers = List.of(
"+12 345 678 9012",
"+123456789012",
"345.678.9012",
"345 678 9012"
);
for (String number : phoneNumbers) {
Matcher matcher = robustPattern.matcher(number);
if(matcher.matches()) {
System.out.println(String.format("Pattern matched for string: %s", number));
}
}
Результат:
Pattern matched for string: +12 345 678 9012
Pattern matched for string: +123456789012
Pattern matched for string: 345.678.9012
Pattern matched for string: 345 678 9012
Заключение
Регулярные выражения могут решить проблему проверки телефонных номеров, но это сложно.
Некоторые страны придерживаются разных стандартов, в то время как некоторые страны принимают и используют несколько форматов одновременно. Это затрудняет написание выражения общего назначения для универсального соответствия телефонным номерам.
В этой статье мы рассмотрели, как сопоставлять телефонные номера с регулярными выражениями в Java, используя несколько различных выражений.
Просмотры: 734
Как с помощью регулярного выражения проверить на корректность телефон? Вы можете воспользоваться следующим регулярным выражением:
String regex = "^\+?[0-9\-\s]*$";
С помощью этого регулярного выражения вы сможете проверить следующие номера телефонов:
- Международные номера телефонов со знаком «+» в начале
- Номера телефонов, разделённые дефисом
- Номера телефонов, разделённые пробелами
- Длина номера телефона при этом не ограничена
Исходный код
public class RegexPhone { public static void main(String[] args) { System.out.println(checkUrl("+380441110044")); // true System.out.println(checkUrl("380441110044")); // true System.out.println(checkUrl("103")); // true System.out.println(checkUrl("911")); // true System.out.println(checkUrl("+7 495 784-63-00")); // true System.out.println(checkUrl("+7_495_784-63-00")); // false } public static boolean checkUrl(String s) { String regex = "^\+?[0-9\-\s]*$"; return s != null && s.matches(regex); } }
Рассмотрим регулярные выражения в Java, затронув синтаксис и наиболее популярные конструкции, а также продемонстрируем работу RegEx на примерах.
- Основы регулярных выражений
- Регулярные выражения в Java
- Примеры использования регулярных выражений в Java
Основы регулярных выражений
Мы подробно разобрали базис в статье Регулярные выражения для новичков, поэтому здесь пробежимся по основам лишь вскользь.
Определение
Регулярные выражения представляют собой формальный язык поиска и редактирования подстрок в тексте. Допустим, нужно проверить на валидность e-mail адрес. Это проверка на наличие имени адреса, символа @
, домена, точки после него и доменной зоны.
Вот самая простая регулярка для такой проверки:
^[A-Z0-9+_.-]+@[A-Z0-9.-]+$
В коде регулярные выражения обычно обозначается как regex, regexp или RE.
Синтаксис RegEx
Символы могут быть буквами, цифрами и метасимволами, которые задают шаблон:
Есть и другие конструкции, с помощью которых можно сокращать регулярки:
- d — соответствует любой одной цифре и заменяет собой выражение [0-9];
- D — исключает все цифры и заменяет [^0-9];
- w — заменяет любую цифру, букву, а также знак нижнего подчёркивания;
- W — любой символ кроме латиницы, цифр или нижнего подчёркивания;
- s — поиск символов пробела;
- S — поиск любого непробельного символа.
Квантификаторы
Это специальные ограничители, с помощью которых определяется частота появления элемента — символа, группы символов, etc:
?
— делает символ необязательным, означает0
или1
. То же самое, что и{0,1}
.*
—0
или более,{0,}
.+
—1
или более,{1,}
.{n}
— означает число в фигурных скобках.{n,m}
— не менееn
и не болееm
раз.*?
— символ?
после квантификатора делает его ленивым, чтобы найти наименьшее количество совпадений.
Примеры использования квантификаторов в регулярных выражениях
Обратите внимание, что квантификатор применяется только к символу, который стоит перед ним.
Также квантификаторов есть три режима:
"А.+а" //жадный режим — поиск самого длинного совпадения
"А.++а" //сверхжадный режим — как жадный, но без реверсивного поиска при захвате строки
"А.+?а" //ленивый режим — поиск самого короткого совпадения
По умолчанию квантификатор всегда работает в жадном режиме. Подробнее о квантификаторах в Java вы можете почитать здесь.
Примеры их использования рассмотрим чуть дальше.
Поскольку мы говорим о регекспах в Java, то следует учитывать спецификации данного языка программирования.
Экранирование символов в регулярных выражениях Java
В коде Java нередко можно встретить обратную косую черту : этот символ означает, что следующий за ним символ является специальным, и что его нужно особым образом интерпретировать. Так,
n
означает перенос строки. Посмотрим на примере:
String s = "Это спецсимвол Java. nОн означает перенос строки.";
System.out.println(s);
Результат:
Это спецсимвол Java.
Он означает перенос строки.
Поэтому в регулярных выражениях для, например, метасимволов, используется двойная косая черта, чтобы указать компилятору Java, что это элемент регулярки. Пример записи поиска символов пробела:
String regex = "\s";
Ключевые классы
Java RegExp обеспечиваются пакетом java.util.regex. Здесь ключевыми являются три класса:
- Matcher — выполняет операцию сопоставления в результате интерпретации шаблона.
- Pattern — предоставляет скомпилированное представление регулярного выражения.
- PatternSyntaxException — предоставляет непроверенное исключение, что указывает на синтаксическую ошибку, допущенную в шаблоне RegEx.
Также есть интерфейс MatchResult, который представляет результат операции сопоставления.
Примеры использования регулярных выражений в Java
e-mail адрес
В качестве первого примера мы упомянули регулярку, которая проверяет e-mail адрес на валидность. И вот как эта проверка выглядит в Java-коде:
List emails = new ArrayList();
emails.add("name@gmail.com");
//Неправильный имейл:
emails.add("@gmail.com");
String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
Pattern pattern = Pattern.compile(regex);
for(String email : emails){
Matcher matcher = pattern.matcher(email);
System.out.println(email +" : "+ matcher.matches());
}
Результат:
name@gmail.com : true
@gmail.com : false
Телефонный номер
Регулярное выражение для валидации номера телефона:
^((8|+7)[- ]?)?((?d{3})?[- ]?)?[d- ]{7,10}$
Эта регулярка ориентирована на российские мобильные номера, а также на городские с кодом из трёх цифр. Попробуйте написать код самостоятельно по принципу проверки e-mail адреса.
IP адрес
А вот класс для определения валидности IP адреса, записанного в десятичном виде:
private static boolean checkIP(String input) {
return input.matches("((0|1\d{0,2}|2([0-4][0-9]|5[0-5]))\.){3}(0|1\d{0,2}|2([0-4][0-9]|5[0-5]))");
}
Правильное количество открытых и закрытых скобок в строке
На каждую открытую должна приходиться одна закрытая скобка:
private static boolean checkExpression(String input) {
Pattern pattern = Pattern.compile("\([\d+/*-]*\)");
Matcher matcher = pattern.matcher(input);
do {
input = matcher.replaceAll("");
matcher = pattern.matcher(input);
} while (matcher.find());
return input.matches("[\d+/*-]*");
}
Извлечение даты
Теперь давайте извлечём дату из строки:
private static String[] getDate(String desc) {
int count = 0;
String[] allMatches = new String[2];
Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d").matcher(desc);
while (m.find()) {
allMatches[count] = m.group();
count++;
}
return allMatches;
}
Проверка:
public static void main(String[] args) throws Exception{
String[] dates = getDate("coming from the 25/11/2020 to the 30/11/2020");
System.out.println(dates[0]);
System.out.println(dates[1]);
}
Результат:
25/11/2020
30/11/2020
А вот использование различных режимов квантификаторов, принцип работы которых мы рассмотрели чуть ранее.
Жадный режим
Pattern pattern = Pattern.compile("a+");
Matcher matcher = pattern .matcher("aaa");
while (matcher.find()){
System.out.println("Найдено от " + matcher.start() +
" до " + (matcher.end()-1));
}
Результат:
Найдено от 0 дo 2
В заданном шаблоне первый символ – a
. Matcher сопоставляет его с каждым символом текста, начиная с нулевой позиции и захватывая всю строку до конца, в чём и проявляется его «жадность». Вот и получается, что заданная стартовая позиция – это 0, а последняя – 2.
Сверхжадный режим
Pattern pattern = Pattern.compile("a++");
Matcher matcher = pattern .matcher("aaa");
while (matcher.find()){
System.out.println("Найдено от " + matcher.start() +
" до " + (matcher.end()-1));
}
Результат:
Найдено от 0 дo 2
Принцип, как и в жадном режиме, только поиск заданного символа в обратном направлении не происходит. В приведённой строке всё аналогично: заданная стартовая позиция – это 0, а последняя – 2.
Ленивый режим
Pattern pattern = Pattern.compile("a+?");
Matcher matcher = pattern .matcher("aaa");
while (matcher.find()){
System.out.println("Найдено от " + matcher.start() +
" до " + (matcher.end()-1));
}
Результат:
Найдено от 0 дo 0
Найдено от 1 дo 1
Найдено от 2 дo 2
Здесь всё просто: самое короткое совпадение находится на первой, второй и третьей позиции заданной строки.
Выводы
Общий принцип использования регулярных выражений сохраняется от языка к языку, однако если мы всё-таки говорим о RegEx в конкретном языке программирования, следует учитывать его спецификации. В Java это экранирование символов, использование специальной библиотеки java.util.regex и её классов.
А какие примеры использования регулярных выражений в Java хотели бы видеть вы? Напишите в комментариях.
A quick guide to how to validate phone numbers in java for different countries such as the USA, IN. Example programs with Regular Expression and Google libphonenumber API.
1. Introduction
In this tutorial, We’ll learn how to validate phone numbers in java. This is to validate mainly the USA and India country phone numbers but after seeing the example you can develop the validation rules for other countries.
This is a common requirement to verify mobile numbers as we do validation for email address validation but java does not have built-in capability to provide such methods. But, We can achieve this with the help of regular expression and google api with libphonenumber.
Let us jump into writing example programs.
2. Regular Expression
Regular expression implementation is a bit tricky because phone number has lots of formats with different extensions.
For example, here are some of the common ways of writing phone numbers for the
USA.
1 2 3 4 5 6 7 |
|
India:
9123124123
Phone Number Validation with Regular Expression
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
Output:
1 2 3 4 5 6 |
|
3. Google libphonenumber Example
If you go with the regex approach, you need to do lots of testing to cover all the corner cases. But, if we have some api that provides this functionality with proper testing that would be good to use in our application.
libphonenumber API is provided by Google as an opensource library that provides the functionalities such as parsing, formatting, validating and storing international phone numbers.
This API is optimized for running on smartphones and also used by the Android framework.
The main advantage of this API is that you can format or validate and parse any country or region mobile numbers.
Class PhoneNumberUtil is a utility for international phone numbers. Functionality includes formatting, parsing, and validation.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Output:
1 |
|
Another Example To Validate USA OR India Phone numbers:
Sample phone numbers
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
Output:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 |
|
PhoneNumberUtil API
5. PhoneNumberType
This api supports all the below types of numbers.
01 02 03 04 05 06 07 08 09 10 11 12 |
|
PhoneNumberUtil.PhoneNumberType
6. Conclusion
In this article, We’ve seen how to validate phone numbers in java using regex and Google open-source api libphonenumber.
GitHub Code
Google API
Как проверить номер телефона в Java (регулярное выражение)
Шаблон регулярных выражений в Java всегда является лучшим методом для проверки номера телефона пользователя. Здесь я предоставляю шаблон регулярного выражения, чтобы определить, находится ли номер телефона в правильном формате, шаблонforce starting with 3 digits follow by a “-” and 7 digits at the end.
Explanation
d = разрешить только цифру
{3} = длина
Все телефонные номера должны быть в формате «xxx-xxxxxxx». Например,
1) 012-6677889 — Пройдено
2) 01216677889 — Не выполнено, «-» отсутствует
3) A12-6677889 — Не выполнено, разрешены только цифры
4) 012-66778899 — Ошибка, только 7 цифр в конце
Полный исходный код проверки номера телефона на Java
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidatePhoneNumber { public static void main(String[] argv) { String sPhoneNumber = "605-8889999"; //String sPhoneNumber = "605-88899991"; //String sPhoneNumber = "605-888999A"; Pattern pattern = Pattern.compile("\d{3}-\d{7}"); Matcher matcher = pattern.matcher(sPhoneNumber); if (matcher.matches()) { System.out.println("Phone Number Valid"); } else { System.out.println("Phone Number must be in the form XXX-XXXXXXX"); } } }