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
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.
+: 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.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
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.
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
[\$ ]+?(\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
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