Проверка правильности номера телефона java

Java Regex to Validate Phone Number

A typical mobile phone number has following component:

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,

If you want to know how we came up with this regex? then please read this full article.

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$"; 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 expression
  • d is mandatory match of 10 digits without any space
  • $ end of expression
Читайте также:  One to one relationship in java

You can make regex more flexible to match between 8 to 11 digits phone number with no space, using this regex:

Regex to match 10 digit Phone Number with WhiteSpaces, Hyphens or No space

String spacesAndHyphenRegex = "^(\\d[- ]?)\\d$"; 

Let’s break the regex and understand,

  • ^ start of expression
  • d is mandatory match of 3 digits
  • [- ]? is optional match of whitespace or hyphen after 3 digits
  • is to repeat the above match d[- ]? two times becomes total 6 digits
  • d 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.

Regex to match 10 digit Phone Number with Parentheses

String parenthesesRegex = "^((\\(\\d\\))|\\d)[- ]?\\d[- ]?\\d$"; 

Let’s break the regex and understand,

  • ^ start of expression
  • (\\(\\d\\))|\\d) is mandatory match of 3 digits with or without parentheses
  • [- ]? is optional match of whitespace or hyphen after after 3 digits
  • \\d[- ]? is mandatory match of next 3 digits followed by whitespace, hyphen or no space
  • \\d 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.

Regex to match 10 digit Phone number with Country Code Prefix

This regex is combined with regex to include parenthesis

String countryCodeRegex = "^(\\+\\d( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"; 

Let’s break the regex and understand,

  • ^ start of expression
  • (\\+\\d( )?)? is optional match of country code between 1 to 3 digits prefixed with + symbol, followed by space or no space.
  • ((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d 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.

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:-

  1. Country Code prefix starts with ‘+’ and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. 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( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"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( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"; 

Let’s break the regex and understand,

  • ^ start of expression
  • (\\+\\d( )?)? is optional match of country code between 1 to 3 digits prefixed with ‘+’ symbol, followed by space or no space.
  • ((\\(\\d\\))|\\d is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \\d[- .]? is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \\d is mandatory group of last 4 digits
  • $ end of expression

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( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"; String singaporeRegex = "^(\\+\\d( )?)?\\d[- .]?\\d$"; 

See Also

Ashish Lahoti avatar

Ashish Lahoti is a Software Engineer with 12+ years of experience in designing and developing distributed and scalable enterprise applications using modern practices. He is a technology enthusiast and has a passion for coding & blogging.

Источник

Регулярные выражения Java: проверяем номер телефона

Регулярные выражения Java: проверяем номер телефона

В этом уроке мы рассмотрим, как проверить номер телефона в Java с помощью регулярных выражений (RegEx).

Телефонные номера трудно проверить. Разные страны имеют разные форматы, а некоторые страны даже используют несколько форматов и кодов стран.

Чтобы проверить номер телефона с помощью регулярных выражений, вам придется написать пару утверждений.

Эти утверждения зависят от вашего проекта, его локализации и стран, в которых вы хотите его применить.

Для стандартной проверки номера телефона в США мы можем использовать длинное, довольно надежное выражение:

4 группы в выражении соответствуют коду страны, номеру региона, номеру абонента и добавочному номеру.

123-456-7890 (123) 456-7890 etc. 

Вы можете написать другое выражение, введя набор правил для групп (в зависимости от страны) и форматов.

Pattern simplePattern = Pattern.compile("^\\+\\d$"); Pattern robustPattern = Pattern.compile("^(\\+\\d\\s)?\\(?\\d\\)?[\\s.-]?\\d[\\s.-]?\\d$"); 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())
Robust Pattern matched for string: +12 345 678 9012

Совпадения здесь могли бы соответствовать нескольким форматам:

Pattern robustPattern = Pattern.compile("^(\\+\\d\\s)?\\(?\\d\\)?[\\s.-]?\\d[\\s.-]?\\d$"); List 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\\s)?\\(?\\d\\)?[\\s.-]?\\d[\\s.-]?\\d$" // Area code, within or without parentheses, // followed by groups of 3-4 numbers with or without hyphens + "| ((\\(\\d\\) ?)|(\\d-))?\\d-\\d" // (+) followed by 10-12 numbers + "|^\\+\\d" ); List 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, используя несколько различных выражений.

Источник

How to Validate Phone Numbers in Java

Write a function that accepts a string, and returns true if it is in the form of a phone number.
Assume that any integer from 0-9 in any of the spots will produce a valid phone number.

Only worry about the following format:
(123) 456-7890 (don’t forget the space after the close parentheses)

"(123) 456-7890" => true "(1111)555 2345" => false "(098) 123 4567" => false 

The solution in Java code#

public class Solution < public static boolean validPhoneNumber(String phoneNumber) < return phoneNumber.matches("\\(\\d\\) \\d-\\d"); > > 
public class Solution < public static boolean validPhoneNumber(String phoneNumber) < char[] cStr = phoneNumber.toCharArray(); if(cStr[0] != '(') return false; if(cStr[4] != ')') return false; if(cStr[5] != ' ') return false; if(cStr[9] != '-') return false; for(int i = 1; i < cStr.length; i++)< if(i != 4 && i != 5 && i != 9)< if(!Character.isDigit(cStr[i])) return false; >> return true; > > 

Test cases to validate our solution#

import org.junit.Test; import static org.junit.Assert.assertEquals; public class PhoneExampleTests < @Test public void tests() < assertEquals(true, Solution.validPhoneNumber("(123) 456-7890")); assertEquals(false, Solution.validPhoneNumber("(1111)555 2345")); assertEquals(false, Solution.validPhoneNumber("(098) 123 4567")); >> 

Additional test cases#

import org.junit.Test; import static org.junit.Assert.assertEquals; public class PhoneTests < @Test public void basicTests() < String msg = "Follow the formatting instructions carefully"; assertEquals(msg, true, Solution.validPhoneNumber("(123) 456-7890")); assertEquals(msg, false, Solution.validPhoneNumber("(1111)555 2345")); assertEquals(msg, false, Solution.validPhoneNumber("(098) 123 4567")); assertEquals(msg, false, Solution.validPhoneNumber("(123)456-7890")); >@Test public void formCharTests() < String msg = "Pay attention to the formatting of the string and surrounding characters"; assertEquals(msg, false, Solution.validPhoneNumber("abc(123)456-7890")); assertEquals(msg, false, Solution.validPhoneNumber("(123)456-7890abc")); assertEquals(msg, false, Solution.validPhoneNumber("abc(123)456-7890abc")); >@Test public void charTests() < String msg = "Be careful with characters surrounding the phone number"; assertEquals(msg, false, Solution.validPhoneNumber("abc(123) 456-7890")); assertEquals(msg, false, Solution.validPhoneNumber("(123) 456-7890abc")); assertEquals(msg, false, Solution.validPhoneNumber("abc(123) 456-7890abc")); >@Test public void badCharTests() < String msg = "Be careful with non-digit characters inside phone number"; assertEquals(msg, false, Solution.validPhoneNumber("(123) 456-78f0")); assertEquals(msg, false, Solution.validPhoneNumber("(123) 4e6-7890")); assertEquals(msg, false, Solution.validPhoneNumber("(*23) 456-7890")); >> 

Источник

Проверка правильности номера телефона java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью