Substring की nth Occurrence Find करना
आप Substring पर Max n+1 Splits के साथ Split करके String में Substring की nth Occurrence Find कर सकते हैं। यदि Resulting List का Size n+1 से Greater है, तो इसका मतलब है कि Substring n से अधिक बार Occur होती है। इसका Index Simple Formula से पाया जा सकता है: Original String की Length - Last Splitted Part की Length - Substring की Length।
उदाहरण
def findnth(string, substring, n):
parts = string.split(substring, n + 1)
if len(parts) <= n + 1:
return -1
return len(string) - len(parts[-1]) - len(substring)
findnth('foobarfobar akfjfoobar afskjdf foobar', 'foobar', 2)
Output:
31
इसमें n 0 से Start होता है। इसे 1-based बनाना काफी Trivial है।
Alternative: find() Loop का उपयोग (अधिक Readable):
def find_nth(string, substring, n, start=0):
"""Find nth Occurrence (0-indexed)"""
for _ in range(n + 1):
idx = string.find(substring, start)
if idx == -1:
return -1
start = idx + 1
return idx - 1 # Last Found Index
# 1-based Version
def find_nth_1based(string, substring, n):
"""Find nth Occurrence (1-indexed)"""
start = 0
for _ in range(n):
idx = string.find(substring, start)
if idx == -1:
return -1
start = idx + 1
return idx
Regex का उपयोग (Overlapping Matches के लिए):
import re
def find_nth_regex(string, substring, n):
matches = [m.start() for m in re.finditer(f'(?={re.escape(substring)})', string)]
return matches[n] if n < len(matches) else -1
# Overlapping Example: 'aaa' में 'aa' की Occurrences
print(find_nth_regex('aaaa', 'aa', 0)) # 0
print(find_nth_regex('aaaa', 'aa', 1)) # 1
print(find_nth_regex('aaaa', 'aa', 2)) # 2