python匹配括号并将括号与括号内内容一起提出,Python-正则表达式在括号之间获取数字...

I need help creating a Regex to get numbers between parenthesis

when my values are between word "PIC" and the "."

I got this records and need to be able to extract values between ()

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"

I have try the below but it doesnt work.

s = "PIC S9(02)V9(05)."

m = re.search(r"\([0-9]+([0-9]))\", s)

print m.group(1)

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值