Validating UPI IDs using Regular Expressions
Last Updated :
03 Apr, 2025
Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID:
- UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.
- It must contain '@'.
- It should not contain whitespace.
- It may or may not contain a dot (.) or hyphen (-).
UPI stands for Unified Payments Interface (UPI).UPI IDs are unique IDs given to each customer.
Examples :
Input: str = ”9136812895@ybl?
Output: True
Input: str = ”MH05DL9023 ”
Output: false
Explanation: It does not contain the "@" symbol.
Input: str = ”ViratKohli101@paytm?
Output: true
Input: str =”rahul.12chauhan1998-1@okicici?
Output: true
Input: str = ”1234567890@upi123456?
Output: true
Input: str = ”Akanksha @ybl ”
Output: false
Explanation: It contains a whitespace.
Approach: The problem can be solved based on the following idea:
Create a regex pattern to validate the number as written below:
regex=”^[a-zA-Z0-9.-]{2, 256}@[a-zA-Z][a-zA-Z]{2, 64}$”
^ : Beginning of the string.
[] Character set :Match any character in the set.
[a-zA-Z0-9.-] : Match any character in the range a-z, A-Z, 0-9, hyphen(-), dot(.).
{2, 256} Quantifier: Match between 2 and 256 of the preceding items.
$: End of the string
Follow the below steps to implement the idea:
- Create regex expression for UPI ID.
- Use Pattern class to compile the regex formed.
- Use the matcher function to check whether the UPI id is valid or not.
- If it is valid, return true. Otherwise, return false.
Below is the implementation of the above approach.
C++
// C++ program to validate the
// UPI ID using Regular
// Expression
#include <bits/stdc++.h>
#include <regex>
using namespace std;
// Function to validate the
// upi_Id Code
string isValidUpi(string upi_Id)
{
// Regex to check valid upi_Id Code
const regex pattern(
"^[a-zA-Z0-9.-]{2,256}@[a-zA-Z][a-zA-Z]{2,64}$");
// If the upi_Id Code
// is empty return false
if (upi_Id.empty()) {
return "false";
}
// Return true if the upi_Id Code
// matched the ReGex
if (regex_match(upi_Id, pattern)) {
return "true";
}
else {
return "false";
}
}
// Driver Code
int main()
{
// Test Case 1:
string str1 = "9136812895@ybl";
cout << isValidUpi(str1) << endl;
// Test Case 2:
string str2 = "rahul.12chauhan1998-1@okicici";
cout << isValidUpi(str2) << endl;
// Test Case 3:
string str3 = "BNZAA2318JM";
cout << isValidUpi(str3) << endl;
// Test Case 4:
string str4 = "934517865";
cout << isValidUpi(str4) << endl;
// Test Case 5:
string str5 = "ViratKohli101@paytm";
cout << isValidUpi(str5) << endl;
// Test Case 6:
string str6 = "Akanksha @ybl";
cout << isValidUpi(str6) << endl;
return 0;
}
Java
// Java program to validate the
// UPI ID using Regular Expression
import java.util.regex.*;
class GFG {
// Function to validate the
// UPI ID(For India Country Only)
public static boolean isValidUpi(String upi_Id)
{
// Regex to check valid upi_Id Code
String regex
= "^[a-zA-Z0-9.-]{2,256}@[a-zA-Z][a-zA-Z]{2,64}$";
// Compile the ReGex
Pattern p = Pattern.compile(regex);
// If the upi_Id Code
// is empty return false
if (upi_Id == null) {
return false;
}
// Pattern class contains matcher()
// method to find matching between
// given MICR Code using regex
Matcher m = p.matcher(upi_Id);
// Return if the upi_Id Code
// matched the ReGex
return m.matches();
}
// Driver Code.
public static void main(String args[])
{
// Test Case 1:
String str1 = "9136812895@ybl";
System.out.println(isValidUpi(str1));
// Test Case 2:
String str2 = "rahul.12chauhan1998-1@okicici";
System.out.println(isValidUpi(str2));
// Test Case 3:
String str3 = "BNZAA2318JM";
System.out.println(isValidUpi(str3));
// Test Case 4:
String str4 = "934517865";
System.out.println(isValidUpi(str4));
// Test Case 5:
String str5 = "ViratKohli101@paytm";
System.out.println(isValidUpi(str5));
// Test Case 6:
String str6 = "Akanksha @ybl";
System.out.println(isValidUpi(str6));
}
}
Python
import re
# Function to validate UPI ID (For India Country Only)
def isValidUpi(str):
# Regex to check valid UPI ID
regex = "^[a-zA-Z0-9.-]{2,256}@[a-zA-Z][a-zA-Z]{2,64}$"
# Compile the ReGex
p = re.compile(regex)
# If the string is empty return false
if (str == None):
return False
# Return if the string matched the ReGex
if(re.search(p, str)):
return True
else:
return False
# Driver code
if __name__ == '__main__':
# Test Case 1:
str1 = "9136812895@ybl"
print(str(isValidUpi(str1)).lower())
# Test Case 2:
str2 = "rahul.12chauhan1998-1@okicici"
print(str(isValidUpi(str2)).lower())
# Test Case 3:
str3 = "Rahul 1998"
print(str(isValidUpi(str3)).lower())
# Test Case 4:
str4 = "934517865"
print(str(isValidUpi(str4)).lower())
# Test Case 5:
str5 = "ViratKohli101@paytm"
print(str(isValidUpi(str5)).lower())
# Test Case 6:
str6 = "Akanksha @ybl"
print(str(isValidUpi(str6)).lower())
C#
using System;
using System.Text.RegularExpressions;
class Program
{
// Function to validate UPI ID (For India Country Only)
static bool IsValidUpi(string str)
{
// Regex to check valid UPI ID
string regex = "^[a-zA-Z0-9.-]{2,256}@[a-zA-Z][a-zA-Z]{2,64}$";
// Check if the input string is empty
if (string.IsNullOrEmpty(str))
{
return false;
}
// Create regex pattern
Regex regexPattern = new Regex(regex);
// Return true if the input matches the regex, else false
return regexPattern.IsMatch(str);
}
// Driver code
static void Main(string[] args)
{
// Test Case 1
string str1 = "9136812895@ybl";
Console.WriteLine(IsValidUpi(str1).ToString().ToLower());
// Test Case 2
string str2 = "rahul.12chauhan1998-1@okicici";
Console.WriteLine(IsValidUpi(str2).ToString().ToLower());
// Test Case 3
string str3 = "Rahul 1998";
Console.WriteLine(IsValidUpi(str3).ToString().ToLower());
// Test Case 4
string str4 = "934517865";
Console.WriteLine(IsValidUpi(str4).ToString().ToLower());
// Test Case 5
string str5 = "ViratKohli101@paytm";
Console.WriteLine(IsValidUpi(str5).ToString().ToLower());
// Test Case 6
string str6 = "Akanksha @ybl";
Console.WriteLine(IsValidUpi(str6).ToString().ToLower());
}
}
JavaScript
// Javascript program to validate
// UPI ID using Regular Expression
// Function to validate the
// upi_Id Code
function isValid_UPI_ID(upi_Id) {
// Regex to check valid
// upi_Id
let regex = new RegExp(/^[a-zA-Z0-9.-]{2,256}@[a-zA-Z][a-zA-Z]{2,64}$/);
// upi_Id
// is empty return false
if (upi_Id == null) {
return "false";
}
// Return true if the upi_Id
// matched the ReGex
if (regex.test(upi_Id) == true) {
return "true";
}
else {
return "false";
}
}
// Driver Code
// Test Case 1:
let str1 = "9136812895@ybl";
console.log(isValid_UPI_ID(str1));
// Test Case 2:
let str2 = "rahul.12chauhan1998-1@okicici";
console.log(isValid_UPI_ID(str2));
// Test Case 3:
let str3 = "BNZAA2318JM";
console.log(isValid_UPI_ID(str3));
// Test Case 4:
let str4 = "MH 05 S 9954";
console.log(isValid_UPI_ID(str4));
// Test Case 5:
let str5 = "ViratKohli101@paytm";
console.log(isValid_UPI_ID(str5));
// Test Case 6:
let str6 = "Akanksha @ybl";
console.log(isValid_UPI_ID(str6));
Outputtrue
true
false
false
true
false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: 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