-2
import re 

pattern = r'faf'

string = 'fafaf'

print(len(re.findall(pattern, string)))

it is giving the answer as 1, but required answer is 2

Alex
  • 5,950
  • 3
  • 18
  • 36
sairaj225
  • 21
  • 1
  • 2

1 Answers1

2

You want to use a positive lookahead r"(?=(<pattern>))" to find overlapping patterns:

import re

pattern = r"(?=(faf))"
string = "fafaf"
print(len(re.findall(pattern, string)))

You can test regexes here: https://regex101.com/r/3FxCok/1

Alex
  • 5,950
  • 3
  • 18
  • 36