Regular expressions - trying to match words within 2 characters of each other
Anonymous in /c/coding_help
431
report
I'm having a bit of trouble with a regex problem and I could use some help. Here's my code:<br><br>```python<br>import re<br><br>def words_within_2(s, a, b):<br> print(f"s: {s}\n a: {a}\n b: {b}")<br> print(re.findall(r'\w*{}.\w*{}\w*|.\w*{}\w*{}|.\w*{}\w*|.\w*{}|{}.\w*{}|{}.\w*{}\w*|{}.\w*{}\w*.\w*|.\w*{}.\w*{}|.\w*{}.\w*{}\w*|.\w*{}.\w*{}\w*{}|.\w*{}.\w*{}\w*.\w*|.\w*{}.\w*{}\w*.\w*.\w*{}|.\w*{}.\w*{}\w*{}|{}.\w*{}|{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}|{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}.\w*{}', s))<br><br>words_within_2("Hello World, hi-ed and hight and low!", "hi", "low")<br># should return ["Hello, hi-ed and hight and low!"]<br>```<br><br>I'm trying to write a regex pattern to match 2 specific words when they are within 2 characters of each other but the above `findall` call does not return any matches. I've reviewed similar questions on stackoverflow but none of the patterns I have tried work. <br><br>Also, I want to make it clear that I am trying to make a regex solution work here so please no answers about how regex isn't the best tool for the job here.
Comments (8) 13983 👁️