Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

regex - Python - Regular expressions get numbers between parenthesis

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...