Could anybody provide me the regular expression for the following patterns?
$1234
$31234.3
$1234.56
$123456.78
$.99
My requirement is the digits before decimal should not exceed 6 and after the decimal point it should not exceed 2 digits. Please help me. Thanks in advance..
To match a dollar sign you need to escape it using a backslash. First we escaped the dollar sign to remove it's special meaning in regex. Then we used \d which matches any digit character and + matches one or more occurrences of the pattern to the left of it so it will match one or more digit characters.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.
Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.
^\$(?=.*\d)\d{0,6}(\.\d{1,2})?$
(?=.*\d)
makes sure that there is at least one digit in the string. Without that, the regex ^\$\d{0,6}(\.\d{1,2})?$
would match the string $
.
Btw, the lookahead need not be this long; even a simple (?=.)
would do, as the regex makes sure that the subsequent characters are indeed valid. Thus, it can be simplified to
^\$(?=.)\d{0,6}(\.\d{1,2})?$
^\$[0-9]{0,6}(\.[0-9]{1,2})?$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With