Skip to main content
 首页 » 编程设计

python之子匹配的位置

2025年05月04日9tuyile006

让我们考虑以下代码。

import re 
 
text = "def oneFunc(x, y): return 0" 
 
pattern = re.compile( 
    r"(?P<DEF_FUNC>def (?P<NAME_FUNC>\w+)\s*\((.*?)\):)|(?P<OTHERS>\w+)" 
) 
 
print('---', text, sep = "\n") 
 
for m in pattern.finditer(text): 
    mdict = m.groupdict() 
 
    print('---', (m.start(), m.end()), sep = "\n") 
 
    for name, textfound in mdict.items(): 
        if textfound != None: 
            print((name, textfound)) 

这给出了以下输出。

--- 
def oneFunc(x, y): return 0 
--- 
(0, 18) 
('NAME_FUNC', 'oneFunc') 
('DEF_FUNC', 'def oneFunc(x, y):') 
--- 
(19, 25) 
('OTHERS', 'return') 
--- 
(26, 27) 
('OTHERS', '0') 

是否可以直接询问子匹配的re位置?例如,我想知道 'oneFunc' 从 4 开始到 11 结束,但我只有当前最大匹配的位置。

请您参考如下方法:

http://docs.python.org/3/library/re.html#re.match.start ?

因此,m.start('NAME_FUNC') 将返回 4 等(当然对于 m.end(…) 也是如此)。