Python - 正则表达式获取括号之间的数字

And*_*pez 2 python regex numbers brackets between

当我的值在单词“PIC”和“.”之间时,我需要帮助创建一个正则表达式来获取括号之间的数字。

我得到了这个记录,需要能够在 () 之间提取值

PIC S9(02)V9(05).    I need this result "02 05"
PIC S9(04).          I need this result "04"
PIC S9(03).          I need this result "03"
PIC S9(03)V9(03).    I need this result "03 03" 
PIC S9(02)V9(03).    I need this result "02 03"
PIC S9(04).          I need this result "04"  
PIC S9(13)V9(03).    I need this result "13 03"
Run Code Online (Sandbox Code Playgroud)

我尝试了以下但它不起作用。

s = "PIC S9(02)V9(05)."
m = re.search(r"\([0-9]+([0-9]))\", s)
print m.group(1)
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 5

您可以使用re.findall()来查找括号内的所有数字:

>>> import re
>>> l = [
...     "PIC S9(02)V9(05).",
...     "PIC S9(04).",
...     "PIC S9(03).",
...     "PIC S9(03)V9(03).",
...     "PIC S9(02)V9(03).",
...     "PIC S9(04).",
...     "PIC S9(13)V9(03)."
... ]
>>> pattern = re.compile(r"\((\d+)\)")
>>> for item in l:
...     print(pattern.findall(item))
... 
['02', '05']
['04']
['03']
['03', '03']
['02', '03']
['04']
['13', '03']
Run Code Online (Sandbox Code Playgroud)

where \(and\)将匹配文字括号(需要用反斜杠转义,因为它们具有特殊含义)。(\d+)是匹配一个或多个数字的捕获组