VOOZH about

URL: https://www.geeksforgeeks.org/dsa/us-currency-validation-using-regular-expressions/

⇱ US currency validation using Regular Expressions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

US currency validation using Regular Expressions

Last Updated : 23 Jul, 2025

Given some  US Currencies, the task is to check if they are valid or not using regular expressions. Rules for the valid Currency are:

  • It should always start with "$".
  • It can contain only digits (0 - 9) and at most one dot.
  • It should not contain any whitespaces and alphabets.
  • Comma Separator (', ') should be there after every three digits interval. 

Examples:

Input: "$0.84"
Output: True

Input: "12345"
Output: False
Explanation: "$" is missing in the starting.

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   
regex = "^\$([0-9]{1, 3}(\, [0-9]{3})*|([0-9]+))(\.[0-9]{2})?$"  

            OR 

regex="^\$(\d{1, 3}(\, \d{3})*|(\d+))(\.\d{2})?$"

Where,

  • ^ : Represents, beginning of the string
  • \$ : Should always start from $
  • \d : Digits should be there
  • \. : dot can be present or not
  • \d{2} : Only digits are allowed after dot

Follow the below steps to implement the idea:

  • Create a regex expression for US Currency.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to check whether the US Currency is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach.


Output
true
true
true
false
false

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  

Related Articles:

Comment