python re how to search end of the digit from sting?

How to search end of the digit from this two srting which is 0.12%?

text1 = '20% of the modern marijuana terpene profile. Myrcene has a distinct earthy, musky flavor, resembling cloves. It is responsible for calming and soothing effects of weed. Myrcene is also found in hops, thyme, mango, lemongrass, guava melon.     0.12%'



text2 = 'The modern marijuana terpene profile. Myrcene has a distinct earthy, musky flavor, resembling cloves. It is responsible for calming and soothing effects of weed. Myrcene is also found in hops, thyme, mango, lemongrass, guava melon.     0.12%'

I tried this which worked for text2 but not getting expected result for text1 like text2

re.search(r'(\d.*)',text)

but my expected result will be 0.12% only

>Solution :

Using (\d.*) captures the first encounter of a digit followed by the rest of the line.

To match the digit with an optional decimal part followed by a percentage sign at the end of the string:

\b\d+(?:\.\d+)?%$

Explanation

  • \b A word boundary to prevent a partial word match
  • \d+(?:\.\d+)? Match 1+ digits with an optional decimal part
  • % Match literally
  • $ End of string

Regex demo

Leave a Reply