CodeNinja101
CodeNinja101

Reputation: 1161

regex that extracts $ and % values from the string

Lets say the string

str1 = "4.1% Cash Back "

str2 = "$44.2 miles "

I want to extract both "4.1%" and "$44.2" from the string. what is the best solution. I tried several methods but didn't go well.

I tried following regex:

  pattern1 = r'(\d+\.\d+*%)'
  pattern2 =  r'$(\d+\.\d+*)'

Upvotes: 0

Views: 51

Answers (3)

Fabricator
Fabricator

Reputation: 12782

Escape $ with \:

pattern = r'\d+(\.\d+)?%|\$\d+(\.\d+)?'

demo

Upvotes: 3

Saurav Gharti Magar
Saurav Gharti Magar

Reputation: 174

no need to escape the '.' sign and You should escape $ sign. Use Patterns as:

pattern1 = r'\d+.\d+%'
pattern2 = r'\$\d+.\d+'

Upvotes: 0

AKS
AKS

Reputation: 19861

Simple is using split:

>>> str1 = "4.1%  Cash Back "
>>> str1.split()[0]
'4.1%'
>>> str2 = "$44.2  miles "
>>> str2.split()[0]
'$44.2'

Upvotes: 0

Related Questions