Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading