Maheswarha Rajagopal
Maheswarha Rajagopal

Reputation: 51

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

I have the string "6324.13(86.36%)", and I'd like to extract out 86.36 only. I used the following regex, 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 containing a string without the brackets. However, I 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 string slicing to remove the last character, but I just want to resolve it within the regex expression itself.

Upvotes: 1

Views: 262

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19242

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']

Upvotes: 1

Related Questions