I have the following string:
fname="VDSKBLAG00120C02 (10).gif"
How can I extract the value 10 from the string fname (using re)?
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 )
\((\d+)\)?int(re.compile(r"\((\d+)\)").search("VDSKBLAG00120C02 (10).gif").group(1))Personally, I'd use this regex:
^.*\(\d+\)(?:\.[^().]+)?$
With this, I can pick the last number in parentheses, just before the extension (if any). It won't go and pick any random number in parentheses if there is any in the middle of the file name. For example, it should correctly pick out 2 from SomeFilmTitle.(2012).RippedByGroup (2).avi. The only drawback is that, it won't be able to differentiate when the number is right before the extension: SomeFilmTitle (2012).avi.
I make assumption that the extension of the file, if any, should not contain ().