Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match dollar sign, money, decimals only

Regex

y = [X: $1.19] [Y: $5.29] [Z 999/1000]
x = re.findall(r"\$[^ ]+", y)

Matches

$1.19] 
$5.29]

Expected Matches

$1.19
$5.29

How can I adjust my regex to match a money amount which could include decimals and must include the dollar sign? - these values can change. E.G:

$x.xx # 'x' representing a number
like image 521
BF_99 Avatar asked Apr 23 '17 11:04

BF_99


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.

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What is $1 regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How do you match a regular expression with digits?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.


2 Answers

You can simply search with following regex.

Regex: \$\d+(?:\.\d+)?

Explanation:

\$: ensures dollar sign followed by

\d+: more or one digits

(?:\.\d+)?: decimal part which is optional

Regex101 Demo

like image 130
Rahul Avatar answered Oct 05 '22 11:10

Rahul


[\$ ]+?(\d+([,\.\d]+)?)

Explanation

[\$ ]+? accept dollar, replace \$ with the currency of your need

(\d+([,\.\d]+)?) digits with comma and period repeated any number of times. Doesn't matter UK numbering system or R

like image 36
ExtractTable.com Avatar answered Oct 05 '22 09:10

ExtractTable.com