使用正则表达式从字符串中提取数字

时间:2013-01-21 11:15:29

标签: python regex

我有以下字符串:

fname="VDSKBLAG00120C02 (10).gif"

如何从字符串10中提取值fname(使用re)?

3 个答案:

答案 0 :(得分:7)

更简单的正则表达式是\((\d+)\)

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

答案 1 :(得分:6)

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

<强>解释

(?<=\() # Assert that the previous character is a (
\d+     # Match one or more digits
(?=\))  # Assert that the next character is a )

答案 2 :(得分:0)

就个人而言,我会使用这个正则表达式:

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

有了这个,我可以在扩展名之前选择括号中的最后一个数字(如果有的话)。如果文件名中间有任何随机数,它将不会在括号中选择任何随机数。例如,它应该从2正确地选择SomeFilmTitle.(2012).RippedByGroup (2).avi。唯一的缺点是,当数字在扩展名之前时,它将无法区分:SomeFilmTitle (2012).avi

我假设文件的扩展名(如果有)不应包含()