Vidak
Vidak

Reputation: 1103

Regex Python extract digits between two strings in a single expression

I want only digits existing between two characters in order to get an integer dollar value, e.g. from string:

"Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

we want to obtain "1730555".

We can use \$(.*)\] to get "1,730,555", but how do we remove the commas in the same expression, while retaining the possibility of arbitrary many commas, ideally getting the number in a single capturing group?

Upvotes: 1

Views: 3197

Answers (2)

Kishore Devaraj
Kishore Devaraj

Reputation: 156

You can try like this

import re
text = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."
match = re.findall(r'\$(.*)]',text)[0].replace(',','')
print match

Upvotes: 2

mrCarnivore
mrCarnivore

Reputation: 5078

You could use split and join:

import re

s = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

match = re.findall(r'\$([\d,]+)', s)
number = ''.join(match[0].split(','))
print(number)

Upvotes: 2

Related Questions