blob
blob

Reputation: 15

How to keep a captured group only in Python regex?

Please accept my apology if this is a dumb question.

I want to make a regex expression that can make the two following changes in Python.

  1. $12345.67890 to 12345.67
  2. $12345 to 12345

What would be an appropriate regex expression to make both changes?

Thank you in advance.

Upvotes: 0

Views: 1456

Answers (2)

farooq
farooq

Reputation: 190

in notepad++ style i would do something like find \$(\d+\.)(\d\d)\d+ Replace \1\2

hope that helps

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

We can try using re.sub here:

inp = "Here is a value $12345.67890 for replacement."
out = re.sub(r'\$(\d+(?:\.\d{1,2})?)\d*\b', '\\1', inp)
print(out)

This prints:

Here is a value 12345.67 for replacement.

Here is an explanation of the regex pattern:

\$                  match $
(                   capture what follows
    \d+             match one or more whole number digits
    (?:\.\d{1,2})?  then match an optional decimal component, with up to 2 digits
)                   close capture group (the output number you want)
\d*                 consume any remaining decimal digits, to remove them
\b                  until hitting a word boundary

Upvotes: 2

Related Questions