我有如下字符串:
fname="VDSKBLAG00120C02 (10).gif"
我该如何使用re
从字符串fname
中提取值10
?
\((\d+)\)
:regex = re.compile(r'\((\d+)\)')
value = int(re.search(regex, fname).group(1))
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 )
个人而言,我会使用这个正则表达式:
^.*\(\d+\)(?:\.[^().]+)?$
通过这个方法,我可以选择括号中的最后一个数字,就在扩展名之前(如果有的话)。 如果文件名中间有任何随机数字,它不会选择任何随机数字。 例如,它应该正确地从SomeFilmTitle.(2012).RippedByGroup (2).avi
中选择出2
。唯一的缺点是,当数字紧挨着扩展名时,它无法区分:SomeFilmTitle (2012).avi
。
我假设文件的扩展名(如果有)不应包含()
。
\((\d+)\)
呢? - Daniel Rosemanint(re.compile(r"\((\d+)\)").search("VDSKBLAG00120C02 (10).gif").group(1))
- Janus Troelsen