[英]Python regex named group (0 or 1 match)
我正在嘗試解析以下行Python:
s='SIP/200259 (In use) has taken 6 calls (last was 8932 secs ago) (order: 0)'
因此,我制作了我的正則表達式:
sip_patt = re.compile(r'''SIP/(?P<ext>\d+).* # Extension
(?P<inuse>In\suse).* # Speaking
has\staken\s(?P<taken>\d+|no).* # Taken
last\swas\s(?P<last>\d+).* # Last Seen
order:\s(?P<order>\d+).* # Order in the queue''', re.X)
這樣會產生期望的結果:
sip_patt.match(s).groups()
('200259', 'In use', '6', '8932', '0')
但是,有時初始字符串可能顯示如下(在括號中請注意“未使用”):
s='SIP/200259 (Not in use) has taken 6 calls (last was 8932 secs ago) (order: 0)'
因此,為了避免所有“ if”和“ elses”,我想稍微更改捕獲邏輯以匹配命名組“ inuse”的0或1個實例,但是這根本行不通。 通過增加 ”?” 或{0,1}在我的命名組旁邊,我總是找不到匹配項:
s='SIP/200259 (In use) has taken 6 calls (last was 8932 secs ago) (order: 0)'
sip_patt = re.compile(r'''SIP/(?P<ext>\d+).* # Extension
(?P<inuse>In\suse)?.* # Speaking
has\staken\s(?P<taken>\d+|no).* # Taken
last\swas\s(?P<last>\d+).* # Last Seen
order:\s(?P<order>\d+).* # Order in the queue''', re.X)
sip_patt.match(s).groups()
('200259', None, '6', '8932', '0')
我想念什么?
你想念什么?
.*
是非常危險的元序列。 它很貪婪,嘗試匹配盡可能多的字符。
那就是你寫的時候
SIP/(?P<ext>\\d+).*
.*
將匹配括號中的任何內容,包括(In use)
。 因為(?P<inuse>In\\suse)?
是一個可選字段,正則表達式計算機在上一個.*
包括此字段.*
如何改正
您可以限制哪些遵循SIP digits
與實例很顯然, In use
與開始(
因此而不是匹配任何東西.*
我們將嘗試像[^(]
這將匹配之外的其他任何東西(
這確保了僅匹配最多(
和In use
中安全匹配(?P<inuse>In\\suse)?
例:
>>> sip_patt = re.compile(r'''SIP/(?P<ext>\d+)[^(]* # Extension
... \((?P<inuse>In\suse)?\).* # Speaking
... has\staken\s(?P<taken>\d+|no).* # Taken
... last\swas\s(?P<last>\d+).* # Last Seen
... order:\s(?P<order>\d+).* # Order in the queue''', re.X)
>>> sip_patt.match(s).groups()
('200259', 'In use', '6', '8932', '0')
注意我限制了?P<inuse>In\\suse)?
在\\( \\)
,以使其與安全性相匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.