Home Regularexpressions Matching Zip code using regular expression
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Matching Zip code using regular expression

Advertisement
This Example describes the way of matching Zip code with the regular expression .For this we are going to make program named Matching_Zipcode.java.

Matching Zip code using regular expression

     

This Example describes the way of matching Zip code with the regular expression .For this we are going to make program named Matching_Zipcode.java. The steps involved in program Matching_Zipcode.java are described below:-

String zipCode = "\\d{5}(-\\d{4})?":-This is the regular expression use to match with Zip code.

matchZip("45643-44435"):-Defining Zip code which is to be matched with the regular expression

Matching_Zipcode.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Matching_Zipcode {

  public static void main(String args[]) {
  matchZip("45643");
  matchZip("45643-44435");

  }
  public static boolean matchZip(String zip) {
  boolean retrival = false;
  String zipCode = "\\d{5}(-\\d{4})?";
  retrival = zip.matches(zipCode);

  String msg = "NO MATCH: Zip code is:" + zip +
  "\n regex for the Zip code is: " + zipCode;

  if (retrival) {
  msg = "MATCH : Zip code is :" + zip + 
  "\n regex for the Zip code is : " + zipCode;
  }

  System.out.println(msg + "\n");
  return retrival;
  }
}

Output of the program:-

MATCH : Zip code is :45643
regex for the Zip code is : \d{5}(-\d{4})?

NO MATCH: Zip code is:45643-44435
regex for the Zip code is: \d{5}(-\d{4})?


Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 30, 2008

Ask Questions?    Discuss: Matching Zip code using regular expression  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com