让我们考虑以下代码。
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(…)
也是如此)。
关于python - 子匹配的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352050/