识别模式匹配的位置

2024-04-26 22:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到字符串匹配的准确位置。。你知道吗

>>> pattern = 'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.group()
'Testworld1'

我需要匹配模式的'Testworld1'字符串中的位置1(第10个字节)。*1。你知道吗


Tags: 字符串testresearch字节match模式group
2条回答

你想做两件事。首先从.*1中创建一个组,然后在访问该组时可以调用.start(),如下所示:

>>> pattern = 'Test.*(1)'
>>> match = re.search(pattern,str1)
>>> match.group(1)
'1'
>>> match.start(1)
9

^{}

>>> pattern = r'Test.*1'
>>> str1='Testworld1'
>>> match = re.search(pattern,str1)
>>> match.end()
10

对于更复杂的应用程序(不只是查找匹配中最后一个字符的最后一个位置),您可能希望改用捕获和^{}

>>> pattern = r'Test.*(11)'
>>> str1='Testworld11'
>>> match = re.search(pattern,str1)
>>> match.start(1) + 1
10

这里,start(n)给出了捕获第n个组的开始索引,其中组由左到右用左括号计数。你知道吗

相关问题 更多 >