繁体   English   中英

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

[英]Python - Regular expressions get numbers between parenthesis

当我的值在单词“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"

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

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

您可以使用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+)是一个匹配一个或多个数字的捕获组

假设您的数字在逻辑上有些关联,因此您可能会想出以下代码(包括解释):

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

在 regex101.comideone.com查看演示

提示:

如果您有列表项,只需使用\\(\\d+\\)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM