-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
  • 6,610
  • 3
  • 20
  • 38
sairaj225
  • 41
  • 1
  • 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
  • 6,610
  • 3
  • 20
  • 38