I wrote a method in which I look for all pattern matches in a string.
def patternSearchResultShow(text, pattern, counter, positions):
print('Text = \'' + text + '\'')
print('Pattern = \'' + pattern + '\'')
print('Number of pattern occurrences: ' + str(counter))
print('The template enters into positions: ' + str(positions))
def patternSearch(text, pattern):
counter = 0
positions = []
for i in range(len(text) - 1):
for j in range(len(pattern)):
if (text[i + j] != pattern[j]):
break
if (j == len(pattern) - 1):
positions.append(i)
counter = counter + 1
patternSearchResultShow(text, pattern, counter, positions)
print('My pattern search:')
text = 'aaaa'
pattern = 'a'
patternSearch(text, pattern)
First test:
text
= 'aaaa'
pattern
= 'a'
My output:
Number of pattern occurrences: 3
The template enters into positions: [0, 1, 2]
Expected output:
Number of pattern occurrences: 4
The template enters into positions: [0, 1, 2, 3]
Ok, to get the above expected result, I changed the following line of code:
for i in range(len(text) - 1):
-> for i in range(len(text)):
Now I have output:
Number of pattern occurrences: 4
The template enters into positions: [0, 1, 2, 3]
Second test:
text
= 'aaaa'
pattern
= 'aa'
My output:
IndexError: string index out of range