Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match dollar amounts

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..

like image 565
MAC Avatar asked Jul 07 '10 09:07

MAC


People also ask

How do you match a dollar sign in regex?

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.

How do I match a number in regex?

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.

What is $1 regex?

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.

How do you match something in regex?

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.


2 Answers

^\$(?=.*\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})?$
like image 52
Amarghosh Avatar answered Sep 29 '22 07:09

Amarghosh


^\$[0-9]{0,6}(\.[0-9]{1,2})?$
like image 44
Chris Avatar answered Sep 29 '22 09:09

Chris