Julio Diaz
Julio Diaz

Reputation: 9437

How do I search for a substring and get match indices while allowing mismatches with Python?

I am looking to find a string allowing for up 2 mismatches. I can do this with:

import regex
regex.findall("(key_string){s<=2}", "kei_strung has two mismatches")

and I get: ['kei_strung']

What I would like to do is to retrieve the start and end position indices, which I could get using re.search(). Unfortunately, I dont know how to allow for 2 mismatches using re.search().

How do you get this outcome?

Upvotes: 0

Views: 97

Answers (1)

Corralien
Corralien

Reputation: 120409

Use regex.finditer instead regex.findall:

for m in regex.finditer("(key_string){s<=2}", "kei_strung has two mismatches"):
    print(f"{m.group()}: [{m.start()}-{m.end()}]")

kei_strung: [0-10]

Upvotes: 1

Related Questions