我需要帮助创建正则表达式来获取括号之间的数字
当我的值在单词“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']
where \(
and \)
将匹配字面括号(需要用反斜杠转义,因为它们具有特殊含义)。(\d+)
is a 捕获组 https://docs.python.org/2/howto/regex.html#grouping它将匹配一个或多个数字。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)