How to validate pin code of India using Regular Expression
Last Updated :
27 Jan, 2023
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.
- It can be only six digits.
- It should not start with zero.
- First digit of the pin code must be from 1 to 9.
- Next five digits of the pin code may range from 0 to 9.
- 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)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read