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

时间:2016-04-14 20:07:58

标签: python regex numbers between brackets

我需要帮助创建一个正则表达式来获取括号之间的数字 当我的价值观在#34; PIC"之间时和#34;。"

我有这些记录,需要能够在()

之间提取值
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"

我试过以下但它不起作用。

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

2 个答案:

答案 0 :(得分:2)

您可以使用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']

其中\(\)与文字括号匹配(需要使用反斜杠进行转义,因为它们具有特殊含义)。 (\d+)是一个匹配一个或多个数字的capturing group

答案 1 :(得分:1)

假设您的号码在某种程度上是逻辑连接的,那么您可能会提出以下代码(包括解释):

import re

string = """
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"
"""
rx = re.compile(
    r"""
    \((\d+)\)       # match digits in parentheses
    [^\n(]+         # match anything not a newline or another opening parenthesis
    (?:\((\d+)\))?  # eventually match another group of digits in parentheses
    """, re.VERBOSE)

for match in re.finditer(rx, string):
    if match.group(2):
        m = ' '.join([match.group(1),match.group(2)])
    else:
        m = match.group(1)
    print m

请参阅 a demo on regex101.com 以及 ideone.com

提示:

如果您有列表项,请转到\(\d+\)