
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Zip Code Validation Using Java Regular Expressions
The zip code can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the zip code and the given input zip code and returns true if they match and false otherwise.
A program that demonstrates this is given as follows:
Example
public class Demo { public static void main(String args[]) { String zipCode = "83592-1537"; String regex = "\d{5}(-\d{4})?"; System.out.println("The zip code is: " + zipCode); System.out.println("Is the above zip code valid? " + zipCode.matches(regex)); } }
Output
The zip code is: 83592-1537 Is the above zip code valid? true
Now let us understand the above program.
The zip code is printed. The Pattern.matches() method matches the regular expression for the zip code and the given input zip code and the result is printed. A code snippet which demonstrates this is as follows:
String zipCode = "83592-1537"; String regex = "\d{5}(-\d{4})?"; System.out.println("The zip code is: " + zipCode); System.out.println("Is the above zip code valid? " + zipCode.matches(regex));
Advertisements