![](/img/trans.png)
[英]How can I match a regex pattern and return captured groups without including empty strings for the groups that aren't captured?
[英]How can I get the position of the captured groups?
這個例子:
r = re.search("a(..)d(.)f", "xxabcdefg")
r.span()
返回整個字符串的(2, 8)
但我想獲得兩個捕獲組的開始和結束位置,所以(2, 4)
和(6, 7)
。
r.span()
方法采用組參數; 每一組都進行了編號,所以使用1
和2
得到的兩個組,的跨度0
對整個文本(其中0
是默認值):
>>> import re
>>> r = re.search("a(..)d(.)f", "xxabcdefg")
>>> r.span()
(2, 8)
>>> r.span(1)
(3, 5)
>>> r.span(2)
(6, 7)
從MatchObject.span()
方法文檔中:
span([group])
對於MatchObject
m ,返回2元組(m.start(group), m.end(group))
。 請注意,如果group對匹配沒有貢獻,則為(-1, -1)
。 組默認為零,即整個匹配項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.