关键词

详解Python re.finditer.start函数:返回匹配的子串开始位置的索引

Python re 模块re.finditer.start 函数的作用与使用方法

1. 作用

re.finditer.start()函数用于返回匹配项在原始字符串中的开始索引位置。

2. 使用方法

re.finditer(pattern, string, flags=0)函数返回一个迭代器,该迭代器包含了对于每一个匹配项的MatchObject的信息,其中可以调用MatchObject的start()函数获得匹配项在原始字符串中的开始索引位置。

3. 实例说明

3.1 实例1:匹配字符串中所有数字的索引位置

import re

string = "I have 3 apples and 2 oranges"
pattern = r'\d'
matches = re.finditer(pattern, string)

for match in matches:
    print(match.start())

# Output: 7, 9, 23, 25

在以上的实例中,我们使用正则表达式r'\d'匹配字符串中的所有数字,返回匹配项在原始字符串中的开始索引位置。

3.2 实例2:匹配字符串中所有元音字母的索引位置

import re

string = "This is a sentence with vowels"
pattern = r'[aeiouAEIOU]'
matches = re.finditer(pattern, string)

for match in matches:
    print(match.start())

# Output: 2, 5, 8, 10, 15, 18, 22, 24, 27

在以上的实例中,我们使用正则表达式r'[aeiouAEIOU]'匹配字符串中的所有元音字母,返回匹配项在原始字符串中的开始索引位置。

本文链接:http://task.lmcjl.com/news/15356.html

展开阅读全文