dimanche 23 décembre 2018

Java phone Number format regex

I am wanting to create a regex for the following number formats: +XXXXXXXXXX. +1(XXX)xxxxxx, +x(xxx)-xxx-xxxx, xxx-xxx-xxxx, xxx-xxxx, and Phone Number:,Phone:,Tel: with all the above formats. All with the output of xxxxxxxxxx

Below is a snippet of my code.

  public static String getPhoneNumber() // returns the phone number formatted as a sequence of digits
    {

        String regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})(?:Tel:)$";
        Pattern pattern = Pattern.compile(regex);
        for (int i = 0; i < line.length(); i++) 
        {
              //if phone number format includes -, . , spaces, + sign in front
              if (line.matches("[+]?\\d?[- .]?(\\([0-9]\\d{2}\\)|[0-9]\\d{2})[- .]?\\d{3}[- .]?\\d{4}$")) {
                phoneNumber = line.replaceAll("[^\\d.]", "").replace("-", "").replace(".", "").replace(" ", "").replace("(", "").replace(")", "")
                        .replace("+", "");

              }
              else
              {
                  getEmailAddress();
              }
                  }
        //System.out.println(phoneNumber);
        return phoneNumber;
    }

Aucun commentaire:

Enregistrer un commentaire