![]() |
VOOZH | about |
Given some Indian Currency Data, the task is to check if they are valid or not using regular expressions. Rules for valid Indian Currency Data are:
Examples:
Input: Rs.12, 34, 567.890
Output: Invalid
Explanation: This currency string has more than two digits in the fractional part, which violates the regular expression pattern that requires exactly two digits in the fractional part. Therefore, this currency string is considered invalid.Input: Rs.123.456
Output: Invalid
Explanation: This currency string has more than two digits in the fractional part, which violates the regular expression pattern that requires exactly two digits in the fractional part. Therefore, this currency string is considered invalid.
Approach: The problem can be solved based on the following idea:
Create a regex pattern to validate the number as written below:
regex =
Where,
- ^ - The caret symbol matches the beginning of the string. This ensures that the pattern only matches currency values that start at the beginning of the string.
- ₹ - This matches the Indian rupee currency symbol.
- [0-9]{1, 3} - This matches 1 to 3 digits.
- ([0-9]{3})* - This matches any number of groups of 3 digits separated by commas. The * character specifies that the preceding pattern (in this case, (, [0-9]{3})) should be matched zero or more times.
- \\. - This matches a decimal point. The \\ is an escape sequence that represents a single backslash, and the dot . matches any character.
- [0-9]{2} - This matches exactly 2 digits.
- $ - The dollar sign matches the end of the string. This ensures that the pattern only matches currency values that end at the end of the string.
- | - The pipe symbol is used to separate two alternative patterns. In this case, it separates the pattern for currency values starting with "₹" from the pattern for currency values starting with "Rs.".
- (Rs\\.\\s)? - This matches an optional "Rs." symbol followed by a space character. The? character specifies that the preceding pattern (in this case, (Rs\\.\\s)) should be matched zero or one time.
By combining these symbols and patterns, we can create a regular expression pattern that matches valid Indian currency.
Follow the below steps to implement the idea:
Below is the code implementation of the above-discussed approach:
Invalid Invalid
Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(1)