![]() |
VOOZH | about |
Given some US Currencies, the task is to check if they are valid or not using regular expressions. Rules for the valid Currency are:
Examples:
Input: "$0.84"
Output: TrueInput: "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:
Below is the implementation of the above approach.
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: