3

I have the following string:

fname="VDSKBLAG00120C02 (10).gif"

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

3 Answers 3

7

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

regex = re.compile(r'\((\d+)\)')
value = int(re.search(regex, fname).group(1))
Sign up to request clarification or add additional context in comments.

Comments

6
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 )

7 Comments

Seems a bit overcomplicated. Why not just \((\d+)\)?
@DanielRoseman: Make a proper answer please. I prefer that solution too.
Using Daniels method: int(re.compile(r"\((\d+)\)").search("VDSKBLAG00120C02 (10).gif").group(1))
@DanielRoseman: I guess it's a matter of preference. This regex corresponds directly to the OP's requirements: "Match a number if it's surrounded by parentheses". Your regex says "Match a pair of parentheses surrounding a number", and you then need to extract the number from that. Both work the same in the end.
The advantage is that you can use the same expression for searching and for replacing.
|
0

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 ().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.