DEV Community

Mpho Mphego
Mpho Mphego

Posted on

Python Regex help?

string = 'R31.99Save\xa05.00'

I would like to strip only 'R31.99' using regular expressions.

Using regular expressions, can someone help on how would I do this?

Oldest comments (3)

Collapse
 
mmphego profile image
Mpho Mphego

Found a solution:

re.findall(r'[R]+\d+\.?\d*', 'R31.99Save\xa05.00')  

Returns: ['R31.99']
Collapse
 
derekenos profile image
Derek Enos

If that first character is only ever going to be a single 'R', you can replace the [R]+ in the regex with just R:

>>> re.findall(r'R\d+\.?\d*', 'R31.99Save\xa05.00')
['R31.99']

Any character in the pattern that doesn't have some special regex meaning will match the character itself.

Collapse
 
gdsoumya profile image
Soumya Ghosh Dastidar

If you are sure about the string being Save you can just use string.split('Save')[0] to get the token you need.