Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
How to validate PAN Card number using Regular Expression
Next article icon

How to validate pin code of India using Regular Expression

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression.

The valid pin code of India must satisfy the following conditions. 

  1. It can be only six digits.
  2. It should not start with zero.
  3. First digit of the pin code must be from 1 to 9.
  4. Next five digits of the pin code may range from 0 to 9.
  5. It should allow only one white space, but after three digits, although this is optional.

Examples:  

Input: num = “132103” 
Output: true 
Explanation: 
The given number satisfies all the above mentioned conditions.

Input: num = “201 305” 
Output: true 
Explanation: 
The given number satisfies all the above mentioned conditions.

Input: num = “014205” 
Output: false 
Explanation: 
The given number start with zero, therefore it is not a valid pin code of India.

Input: num = “1473598” 
Output: false 
Explanation: 
The given number contains seven digits, therefore it is not a valid pin code of India.  

Approach: This problem can be used by using Regular Expression.  

1. Get the number.

2. Create a regular expression to validate pin code of India as mentioned below: 

  regex = "^[1-9]{1}[0-9]{2}\\s{0, 1}[0-9]{3}$";

Where: 

  • ^ represents the starting of the number.
  • [1-9]{1} represents the starting digit in the pin code ranging from 1 to 9.
  • [0-9]{2} represents the next two digits in the pin code ranging from 0 to 9.
  • \\s{0, 1} represents the white space in the pin code that can occur once or never.
  • [0-9]{3} represents the last three digits in the pin code ranging from 0 to 9.
  • $ represents the ending of the number.

3. Match the given number with the regex, in Java, this can be done by using Pattern.matcher().

4. Return true if the number matches with the given regex, else return false.

Below is the implementation of the above approach.  

C++




// C++ program to validate the pin code
// of India using Regular Expression.
#include <bits/stdc++.h>
using namespace std;
 
// Function to validate the pin code of India.
bool isValidPinCode(string pinCode)
{
     
    // Regex to check valid pin code of India.
    const regex pattern("^[1-9]{1}[0-9]{2}\\s{0,1}[0-9]{3}$");
 
    // If the pin code is empty
    // return false
    if (pinCode.empty())
    {
        return false;
    }
 
    // Return true if the pin code
    // matched the ReGex
    if (regex_match(pinCode, pattern))
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
void print(bool n)
{
    if (n == 0)
    {
        cout << "False" << endl;
    }
    else
    {
        cout << "True" << endl;
    }
}
 
// Driver Code.
int main()
{
     
    // Test Case 1:
    string num1 = "132103";
    cout << num1 + ": ";
    print(isValidPinCode(num1));
 
    // Test Case 2:
    string num2 = "201 305";
    cout << num2 + ": ";
    print(isValidPinCode(num2));
 
    // Test Case 3:
    string num3 = "014205";
    cout << num3 + ": ";
    print(isValidPinCode(num3));
 
    // Test Case 4:
    string num4 = "1473598";
    cout << num4 + ": ";
    print(isValidPinCode(num4));
 
    return 0;
}
 
// This code is contributed by nirajgusain5
 
 

Java




// Java program to validate the pin code
// of India using Regular Expression.
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the pin code of India.
    public static boolean isValidPinCode(String pinCode)
    {
 
        // Regex to check valid pin code of India.
        String regex
            = "^[1-9]{1}[0-9]{2}\\s{0,1}[0-9]{3}$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the pin code is empty
        // return false
        if (pinCode == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given pin code
        // and regular expression.
        Matcher m = p.matcher(pinCode);
 
        // Return if the pin code
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String num1 = "132103";
        System.out.println(
            num1 + ": "
            + isValidPinCode(num1));
 
        // Test Case 2:
        String num2 = "201 305";
        System.out.println(
            num2 + ": "
            + isValidPinCode(num2));
 
        // Test Case 3:
        String num3 = "014205";
        System.out.println(
            num3 + ": "
            + isValidPinCode(num3));
 
        // Test Case 4:
        String num4 = "1473598";
        System.out.println(
            num4 + ": "
            + isValidPinCode(num4));
    }
}
 
 

Python3




# Python3 program to validate the 
# pin code of India using Regular
# Expression.
import re
 
# Function to validate the pin code
# of India.
def isValidPinCode(pinCode):
     
    # Regex to check valid pin code
    # of India.
    regex = "^[1-9]{1}[0-9]{2}\\s{0,1}[0-9]{3}$";
 
    # Compile the ReGex
    p = re.compile(regex);
     
    # If the pin code is empty
    # return false
    if (pinCode == ''):
        return False;
         
    # Pattern class contains matcher() method
    # to find matching between given pin code
    # and regular expression.
    m = re.match(p, pinCode);
     
    # Return True if the pin code
    # matched the ReGex else False
    if m is None:
        return False
    else:
        return True
 
# Driver code
if __name__ == "__main__":
     
    # Test case 1
    num1 = "132103";
    print(num1, ": ", isValidPinCode(num1));
     
    # Test case 2:
    num2 = "201 305";
    print(num2, ": ", isValidPinCode(num2));
     
    # Test case 3:
    num3 = "014205";
    print(num3, ": ", isValidPinCode(num3));
     
    # Test case 4:
    num4 = "1473598";
    print(num4, ": ", isValidPinCode(num4));
     
# This code is contributed by AnkitRai01
 
 

C#




// C# program to validate the
//the pin code of India
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
 
  // Main Method
  static void Main(string[] args)
  {
 
    // Input strings to Match
    //the pin code of India
    string[] str={"132103","201 305","014205","1473598"};
    foreach(string s in str) {
      Console.WriteLine( isValidPinCode(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
  // method containing the regex
  public static bool isValidPinCode(string str)
  {
    string strRegex = @"^[1-9]{1}[0-9]{2}\s{0,1}[0-9]{3}$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
      return (true);
    else
      return (false);
  }
}
// This code is contributed by Rahul Chauhan
 
 

Javascript




Javascript// Javascript program to validate
// Pincode of India using Regular Expression
 
// Function to validate the
// Pincode of India
function isValidPinCode(str) {
    // Regex to check valid
    // Pincode of India
    let regex = new RegExp(/^[1-9]{1}[0-9]{2}\s{0,1}[0-9]{3}$/);
 
    // if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "132103";
console.log(isValidPinCode(str1));
 
// Test Case 2:
let str2 = "201 305";
console.log(isValidPinCode(str2));
 
// Test Case 3:
let str3 = "014205";
console.log(isValidPinCode(str3));
 
// Test Case 4:
let str4 = "1473598";
console.log(isValidPinCode(str4));
 
 
Output: 
132103: true 201 305: true 014205: false 1473598: false

 

Time Complexity : O(1)

Space Complexity : O(1)



Next Article
How to validate PAN Card number using Regular Expression
author
prashant_srivastava
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • CPP-regex
  • java-regular-expression
Practice Tags :
  • Pattern Searching

Similar Reads

  • How to validate IFSC Code using Regular Expression
    Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
    8 min read
  • How to validate ISIN using Regular Expressions
    ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
    6 min read
  • How to validate PAN Card number using Regular Expression
    Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
    6 min read
  • How to validate MAC address using Regular Expression
    Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
    6 min read
  • How to validate Indian Passport number using Regular Expression
    Given a string str of alphanumeric characters, the task is to check whether the given string is a valid passport number or not by using Regular Expression. A valid passport number in India must satisfy the following conditions: It should be eight characters long.The first character should be an uppe
    5 min read
  • How to validate CVV number using Regular Expression
    Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
    5 min read
  • How to validate Indian driving license number using Regular Expression
    Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving licen
    7 min read
  • How to validate a domain name using Regular Expression
    Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long
    6 min read
  • How to validate an IP address using Regular Expressions in Java
    Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Inpu
    3 min read
  • How to validate Hexadecimal Color Code using Regular Expression
    Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences