I'm trying to find the indices of a pattern in a sentence. The pattern can be a word or a combination of words. I've used regular expressions for this. But I've some edge cases to handle. import re word = "is" s = "Is (valid) is (valid), is-not (not valid), is. (valid) is!, (valid), is_1 (not valid) ,is (valid), is? (valid)" iters = re.finditer(r"\b" + re.escape(word) + r"\b", s, re.I) indices = [m.start(0) for m in iters] print(indices) This outputs [0, 11, 23, 43, 55, 87, 99] As you can see, the occurrence of is with certain symbols are required matches and some are not. Here is the list of valid symbols which can be taken into consideration for a match. [" ", ",", ".", "!", "?"] How to avoid the 3rd match (is-not) from the results? Continue reading...