Java phone number regexp

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

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
Читайте также:  Просмотр массива $GLOBALS

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.

Источник

Validate Phone Numbers With Java Regex

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

Читайте также:  Mail test

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

Sometimes, we need to validate text to ensure that its content complies with some format. In this quick tutorial, we’ll see how to validate different formats of phone numbers using regular expressions.

2. Regular Expressions to Validate Phone Numbers

2.1. Ten-Digit Number

Let’s start with a simple expression that will check if the number has ten digits and nothing else:

@Test public void whenMatchesTenDigitsNumber_thenCorrect() < Pattern pattern = Pattern.compile("^\\d$"); Matcher matcher = pattern.matcher("2055550125"); assertTrue(matcher.matches()); >

This expression will allow numbers like 2055550125.

2.2. Number With Whitespaces, Dots or Hyphens

In the second example, let’s see how we can allow optional whitespace, dots, or hyphens (-) between the numbers:

@Test public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() < Pattern pattern = Pattern.compile("^(\\d[- .]?)\\d$"); Matcher matcher = pattern.matcher("202 555 0125"); assertTrue(matcher.matches()); >

To achieve this extra goal (optional whitespace or hyphen), we’ve simply added the characters:

This pattern will allow numbers like 2055550125, 202 555 0125, 202.555.0125, and 202-555-0125.

2.3. Number With Parentheses

Next, let’s add the possibility to have the first part of our phone between parentheses:

@Test public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() < Pattern pattern = Pattern.compile"^((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"); Matcher matcher = pattern.matcher("(202) 555-0125"); assertTrue(matcher.matches()); >

To allow the optional parenthesis in the number, we’ve added the following characters to our regular expression:

Читайте также:  Css stylesheets in html

This expression will allow numbers like (202)5550125, (202) 555-0125 or (202)-555-0125. Additionally, this expression will also allow the phone numbers covered in the previous example.

2.4. Number With International Prefix

Finally, let’s see how to allow an international prefix at the start of a phone number:

@Test public void whenMatchesTenDigitsNumberPrefix_thenCorrect() < Pattern pattern = Pattern.compile("^(\\+\\d( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$"); Matcher matcher = pattern.matcher("+111 (202) 555-0125"); assertTrue(matcher.matches()); > 

To permit the prefix in our number, we have added to the beginning of our pattern the characters:

This expression will enable phone numbers to include international prefixes, taking into account that international prefixes are normally numbers with a maximum of three digits.

3. Applying Multiple Regular Expressions

As we’ve seen, a valid phone number can take on several different formats. Therefore, we may want to check if our String complies with any one of these formats.

In the last section, we started with a simple expression and added more complexity to achieve the goal of covering more than one format. However, sometimes it’s not possible to use just one expression. In this section, we’ll see how to join multiple regular expressions into a single one.

If we are unable to create a common regular expression that can validate all the possible cases that we want to cover, we can define different expressions for each of the cases and then use them all together by concatenating them with a pipe symbol (|).

Let’s see an example where we use the following expressions:

@Test public void whenMatchesPhoneNumber_thenCorrect() < String patterns = "^(\\+\\d( )?)?((\\(\\d\\))|\\d)[- .]?\\d[- .]?\\d$" + "|^(\\+\\d( )?)?(\\d[ ]?)\\d$" + "|^(\\+\\d( )?)?(\\d[ ]?)(\\d[ ]?)\\d$"; String[] validPhoneNumbers = ; Pattern pattern = Pattern.compile(patterns); for(String phoneNumber : validPhoneNumbers) < Matcher matcher = pattern.matcher(phoneNumber); assertTrue(matcher.matches()); >>

As we can see in the above example, by using the pipe symbol, we can use the three expressions in one go, thus allowing us to cover more cases than with just one regular expression.

4. Conclusion

In this article, we’ve seen how to check whether a String contains a valid phone number using different regular expressions. We’ve also learned how to use multiple regular expressions at the same time.

As always, the full source code of the article is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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