Extracting number from string using regular expressions

I have the following line:

fname="VDSKBLAG00120C02 (10).gif"

      

How do I extract a value 10

from a string fname

(using re

)?

+3


source to share


3 answers


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 )

      

+6


source


Simplest regular expression \((\d+)\)

:



regex = re.compile(r'\((\d+)\)')
value = int(re.search(regex, fname).group(1))

      

+7


source


Personally, I would use this regex:

^.*\(\d+\)(?:\.[^().]+)?$

      

That being said, I can select the last number in the parentheses just before the expansion (if any). It will neither match nor accept an arbitrary number in parentheses if there are any characters in the middle of the filename. For example, he must choose the right one 2

from SomeFilmTitle.(2012).RippedByGroup (2).avi

. The only drawback is that he will not be able to distinguish when the number just before the extension: SomeFilmTitle (2012).avi

.

My guess is that the file extension, if any, shouldn't contain ()

.

0


source







All Articles