DEV Community

Mpho Mphego
Mpho Mphego

Posted on

1

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?

Top comments (3)

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.

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay