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");

System.out.println(number);

Program output.

(123) 456-7890

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.