Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Regularexpressions Matching Address using regular expressions

 
 

Share on Google+Share on Google+

Matching Address using regular expressions

Advertisement
This Example describes the way to match address using regular expression.For this we are going to make program named Matching.java.

Matching Address using regular expressions

     

This Example describes the way to match address using regular expression.For this we are going to make program named Matching.java. The steps involved in program Matching.java are described below:-

String name = "\\p{Upper}":- Creating expression for name.Here {upper} means all the name should be in upper case.

String namePattern = "("+name +"){2,3}":-Causes the resulting regular expression to match from 2 to 3 repetitions of the preceding regular expression

String regex = "^"+ namePattern + "\\w+ .*, \\w+ "+ zipCode + "$":-Combining the above 2 string and making a single expression.

retrival = address.matches(regex):-By this we are attempting to match the entire input against the pattern.

 

 

 

Matching.java:-

public class Matching {

  public static void main(String[] args) {
  match("abc 888 rohini, NY 64332");
 match("ABC 888 south ex, NY 64332-4453");
  }
  public static boolean match(String address) {
 
 boolean retrival = false;

  String name = "\\p{Upper}";

  String namePattern = "("+name +"){2,3}";

  String zipCode = "\\d{5}(-\\d{4})?";

 String regex = "^"+ namePattern + "\\w+ .*, \\w+ "
 + zipCode + "$";
  
  retrival = address.matches(regex);

  String msg = "NO MATCH\npattern:\n " + address + "\nregex is:\n "
  + regex;

  if (retrival) {
  msg = "MATCH\npattern:\n " + address + "\nregex is:\n "
  + regex;
  }
  System.out.println(msg + "\r\n");
  return retrival;
  }
  }

Output of the program:-

NO MATCH
pattern:
abc 888 rohini, NY 64332
regex is:
^(\p{Upper}){2,3}\w+ .*, \w+ \d{5}(-\d{4})?$

MATCH
pattern:
ABC 888 south ex, NY 64332-4453
regex is:
^(\p{Upper}){2,3}\w+ .*, \w+ \d{5}(-\d{4})?$


DownLoad Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



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 27, 2008

Related Tutorials

Discuss: Matching Address using regular expressions  

Post your Comment


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