Java format string to phone number with dashes – (123) 456-6789 pattern

Learn to format string to phone number pattern which is (123) 456-6789. This conversion is generally required in applications where customer’s data has to be displayed and phone number is part of this data.

How to format string to phone number with dashes

To format string to phone number –

  1. Break the string to 3 groups using regular expression '(\\d{3})(\\d{3})(\\d+)'.
  2. First group contains 3 digits. Second contains 3 digits and last group contains all remaining digits.
  3. Create a formatted string using these groups in '($1) $2-$3' pattern.

Given below is a Java program which converts a string to phone number in (###) ###-#### format.

String input = "1234567890";

String number = input.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");


Program output.

(123) 456-7890

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.