Steven Matthews
Steven Matthews

Reputation: 11285

Grabbing number next to a dollar sign with optional thousands and decimals

I am trying to grab a number that can be in the format $5,000.23 as well as say, $22.43 or $3,000

Here's my regular expression, this is in PHP.

preg_match('/\$([0-9]+)([\.,]*)?([0-9]*)?([\.])?([0-9]*)?/', $blah, $blah2);

It seems to match numbers in the format $5,500.23 perfectly fine, however it doesn't seem to match any other numbers well, like $0.

How do I make everything optional? Shouldn't grouping () and using a question mark do that?

Upvotes: 3

Views: 45

Answers (1)

SierraOscar
SierraOscar

Reputation: 17637

This should do the trick:

\$[\d,.]*[\d]

Regular expression visualization

Debuggex Demo


Specific PHP Example:

$re = "/\\$[\\d,.]*[\\d]/"; 
$str = "\$1 klsjdfgsjdfg \$100 kjdfhglsjdfg \$1,000 jljsdfg \$1,000.00 ldfjhsdf"; 

preg_match_all($re, $str, $matches);

Regex 101 Demo

Upvotes: 1

Related Questions