Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a number from a string using regular expressions

Tags:

python

regex

I have the following string:

fname="VDSKBLAG00120C02 (10).gif"

How can I extract the value 10 from the string fname (using re)?

like image 860
Akhil Thayyil Avatar asked Jul 18 '26 15:07

Akhil Thayyil


2 Answers

A simpler regex is \((\d+)\):

regex = re.compile(r'\((\d+)\)')
value = int(re.search(regex, fname).group(1))
like image 166
Daniel Roseman Avatar answered Jul 21 '26 07:07

Daniel Roseman


regex = re.compile(r"(?<=\()\d+(?=\))")
value = int(re.search(regex, fname).group(0))

Explanation:

(?<=\() # Assert that the previous character is a (
\d+     # Match one or more digits
(?=\))  # Assert that the next character is a )
like image 36
Tim Pietzcker Avatar answered Jul 21 '26 08:07

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!