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

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial