VOOZH about

URL: https://www.geeksforgeeks.org/dsa/validating-upi-ids-using-regular-expressions/

⇱ Validating UPI IDs using Regular Expressions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Validating UPI IDs using Regular Expressions

Last Updated : 23 Jul, 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.


Output
true
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)  

Comment