Home > Back-end >  I would like to use regex in python to match a US dollar amount
I would like to use regex in python to match a US dollar amount

Time:06-25

I'm pretty new to python and regex, so forgive me if this in elementary. I am trying to match a pattern to allow for unlimited numbers on the left side of the decimal and two on the right. This is the pattern I'm dealing with.

$44.01Bobby N. ...1111

It might also be something like.

$4354.01Bobby N. ...1241

I am able to match the 44.01 by simply typing this, which is what I want.

\d*\.\d\d

However, I end out matching .11 as well, which I don't want.

CodePudding user response:

The problem is you are using \d* which matches: no digit, one digit or more that one digits, so .11 is a valid match. To ensure matching at least one digit before the . try using \d \.\d\d. The \d matches one or more than one digit.

CodePudding user response:

You can also use curly braces for the right side numbers to indicate you want exactly 2 instances of \d—but, of course, if you want to save a keystroke and readability isn't an issue, using \d\d works as well:

\d \.\d{2}
  • Related