Home > database >  Extract a specific part of a string that contains bracket and percentage symbol using regex
Extract a specific part of a string that contains bracket and percentage symbol using regex

Time:03-24

I'm having the following string 6324.13(86.36%)and I'd like to extract out the 86.36 only. I used the following regex method but the output still comes with the bracket and percentage character.

re.search('\((.*?)\)',s).group(0) -> (86.36%)

I used the following instead but it returns an array without the brackets but still can't remove the percentage character.

re.findall('\((.*?)\)',s) -> ['86.36%']

I'm just not sure how to modify the regex to remove that % as well. I know I can use python [:-1] method to remove the last character but I just want to resolve it within the regex expression itself.

CodePudding user response:

Add a percentage sign to the regular expression, so that it's omitted from the capture group:

import re
s = "6324.13(86.36%)"
result = re.findall('\((.*?)%\)',s)
print(result) # Prints ['86.36']
  • Related