I just want to print the phone number in the form of (123)456-55778 for my result to be valid. I have tried a couple of thing but I am not arriving to the answer. Please help.

import java.util.*;
public class TokenizingTelephoneNumbers {

    /**
     * @param args the command line arguments
     */
    public static boolean validatePhone(String phone)
    {
        return phone.matches("([1-9]\\d{2}) [1-9]\\d{2}-\\d{4}");
                          //("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}"); book example
    }
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter phone:");
        String phone = input.nextLine();
         
        System.out.println("\nResults:");
        
        if(!validatePhone(phone))
        {
        System.out.println("Invlid phone number");
        }
        else
        System.out.println(" Your phone number is correct.\n"
                + " Thank you");
    }
}

I have tried a couple of thing

Show what you have done and its output and explain what is wrong.

First trial ("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}"); prints 132-145-4456 as valid
Second trial ("[1-9]\\d{2}[1-9]\\d{2}-\\d{4}"); prints 132 145-4456 as valid
third trial ("([1-9]\\d{2})" + "[1-9]\\d{2}-\\d{4}"); prints 132 145-4456 as valid
forth trial ("([1-9])\\d{2}[1-9]\\d{2}-\\d{4}"); prints error
fifth trial ("[1-9]\\d{4}[1-9]\\d{2}-\\d{4}"); prints error
sixth trial ("([1-9]\\d{2})[1-9]\\d{2}-\\d{4}");
I just do not end up with (123)456 5566 Parenthesis around area code.
I know the code works fine except for the formating.

A couple of things to consider.
First, [1-9]\d{2} is the same as \d{3} . So you can simply that expression a bit.

Second, parenthesis are special characters in regex. You need to escape them if you want to use them as character literals in a pattern.

Edited 5 Years Ago by Ezzaral: n/a

This article has been dead for over six months. Start a new discussion instead.