Enigmatic
Enigmatic

Reputation: 4148

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

Upvotes: 15

Views: 52334

Answers (4)

Rahul
Rahul

Reputation: 2738

You can simply search with following regex.

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

Explanation:

\$: ensures dollar sign followed by

\d+: one or more digits

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

Regex101 Demo

Upvotes: 25

ExtractTable.com
ExtractTable.com

Reputation: 811

[\$ ]+?(\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

Upvotes: 1

Muhammad Hamza Ali
Muhammad Hamza Ali

Reputation: 139

Best Regular Expressions for this case is

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

Explanation

\$ shows it should starts with a dollar sign

\d+ matches all numbers before decimal

(?:.(\d+)) matches if there are any numbers after the decimal. For example in $1.12 it would match .12 and capture 12 (part after the decimal) . If the money is $1. it would only match $1 it would not match .

Regular Expression tester, library, tutorials and cheat sheet.

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107297

Just replace the space within your negated-character class with closed bracket:

In [37]: x = re.findall(r"\$[^\]]+", y)

In [38]: x
Out[38]: ['$1.19', '$5.29'] 

Upvotes: 4

Related Questions