Java – Format a String in Phone Number Format with Hyphens

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

1. Format String to ‘(###) ###-####‘ Pattern

To format string to phone number –

  • Break the string into 3 groups using regular expression '(\\d{3})(\\d{3})(\\d+)'.
  • The first group contains 3 digits. The second contains 3 digits, and the last group contains all remaining digits.
  • Create a formatted string using these groups.

Given below is a Java program that converts a string to a phone number in (###) ###-#### format. It uses the String.replaceFirst() method for matching and replacing the substring using regex.

String input = "1234567890";

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

2. Format String to ‘###-###-####‘ Pattern

We can reuse the logic discussed in the previous section to capture the groups and format them into any pattern, such as ###-###-####.

String input = "1234567890";

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

Happy Learning !!

Sourcecode on Github

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