Python – Regular expressions get numbers between parenthesis

You can use re.findall() to find all numbers within the parenthesis:

>>> 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']

where \( and \) would match the literal parenthesis (needed to be escaped with a backslash because of the special meaning they have). (\d+) is a capturing group that would match one or more digits.

Leave a Comment