Irfan Ghaffar7
Irfan Ghaffar7

Reputation: 1185

String filtering commas and numbers

I want to filter a string in Python, to get only commas , and numbers [0-9].

import re
x="$HGHG54646JHGJH,54546654"
m=re.sub("[^0-9]","",x)
print(m)

The result is:

5464654546654

instead of:

54646,54546654

Upvotes: 0

Views: 542

Answers (1)

miradulo
miradulo

Reputation: 29690

With your current code, you simply match [0-9]. Simply add a comma , as a valid character, and use a backslash to escape to the literal (\,):

import re
x="$HGHG54646JHGJH,54546654"
m=re.sub("[^0-9\,]","",x)
print(m)

Outputs:

54646,54546654

The docs have further information regarding other special characters that must be escaped with a backslash to acquire the literal, such as ? and *.

Upvotes: 6

Related Questions