Tuesday, December 23, 2014

Java using in Removing whitespaces and Matching Phone Numbers pro



Removing whitespaces

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
             {
   public static void main(String[] argv) throws Exception 
  {
      String ExString = "This is a Java program. 
      This is another Java Program.";
      String result=removeDuplicateWhitespace(ExString);
      System.out.println(result);
   }
   public static CharSequence 
   removeDuplicateWhitespace(CharSequence inputStr) 
  {
      String patternStr = "\\s+";
      String replaceStr = " ";
      Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
 return matcher.replaceAll(replaceStr);
   }
}

Matching Phone Numbers

public class MatchPhoneNumber 
{
   public static void main(String args[]) 
  {
      isPhoneValid("1-999-585-4009");
      isPhoneValid("999-585-4009");
      isPhoneValid("1-585-4009");
      isPhoneValid("585-4009");
      isPhoneValid("1.999-585-4009");
      isPhoneValid("999 585-4009");
      isPhoneValid("1 585 4009");
      isPhoneValid("111-Java2s");
   }
   public static boolean isPhoneValid(String phone) 
  {
      boolean retval = false;
      String phoneNumberPattern = 
      "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
      retval = phone.matches(phoneNumberPattern);
      String msg = "No match: pattern:" + phone
      + "\r\n regex: " + phoneNumberPattern;
      if (retval)
      {
         msg = " Match: pattern:" + phone 
         + "\r\n regex: " + phoneNumberPattern;
      }
      System.out.println(msg + "\r\n");
      return retval;
   }
}

No comments:

Post a Comment