在Python中,你可以使用内置的re模块来查找所有匹配子串的位置。以下是一个使用re.finditer方法查找所有匹配子串位置的例子:
import re
def find_all_occurrences(text, pattern):
matches = re.finditer(pattern, text)
start_positions = [match.start() for match in matches]
return start_positions
text = "This is a test string for searching substrings"
pattern = "test"
positions = find_all_occurrences(text, pattern)
print(positions) # 输出子串"test"在text中所有出现的起始位置
如果不需要使用正则表达式,而只是想找到字符串中所有的子串位置,可以使用如下方法:
def find_all_occurrences_no_regex(text, sub_text):
start = 0
positions = []
while True:
start = text.find(sub_text, start)
if start == -1:
break
positions.append(start)
start += len(sub_text) # 移动到子串之后继续查找
return positions
text = "This is a test string for searching substrings"
sub_text = "test"
positions = find_all_occurrences_no_regex(text, sub_text)
print(positions) # 输出子串"test"在text中所有出现的起始位置
两种方法都可以找出所有匹配的子串位置。第一种方法使用了正则表达式,第二种方法则是使用Python字符串的find方法。
3702

被折叠的 条评论
为什么被折叠?



