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
CodePudding user response:
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
\bA word boundary to prevent a partial word match\d (?:\.\d )?Match 1 digits with an optional decimal part%Match literally$End of string
CodePudding user response:
\b\d (?:\.\d )?%$
This should work.
\b Returns a match where the specified characters are at the beginning or at the end of a word
\d Returns a match where the string contains digits (numbers from 0-9) [Checks for digits basically]
One or more occurrences
() Capture and group
?Zero or one occurrences\dReturns a match where the string contains digits (numbers from 0-9)One or more occurrences
? Zero or one occurrences
%$ Checks if ends with %
Some explanation taken from w3schools
