Skip to main content
 首页 » 编程设计

python之识别模式匹配的位置

2025年05月04日11webabcd

我需要找到字符串匹配的确切位置..

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

我需要匹配模式 .*1 的“Testworld1”字符串中 1(第 10 个字节)的位置。

请您参考如下方法:

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

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