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

Akh*_*yil 3 python regex

我有以下字符串:

fname="VDSKBLAG00120C02 (10).gif"
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*man 7

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

regex = re.compile(r'\((\d+)\)')
value = int(re.search(regex, fname).group(1))
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 6

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

说明:

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

  • 似乎有点过于复杂.为什么不只是`\((\ d +)\)`? (2认同)