比较特定事件的字符串和字符串列表

Compare a string and a list of strings for a certain occurance

我有一个字符串,"spaghet in insert in impossible(banana)"(示例字符串。),我将其称为 testString。我还有一个字符串中每个“单词”的列表,使用以下代码生成:

stringList = re.split("(\W)", testString)
for item in stringList:
    if item == "":
        stringList.remove(item)

列表如下所示: ["spaghet", "in", "insert", "in", "impossible", "(", "banana", ")"]
我需要一个函数,它可以自己给出 string 中每次出现单词“in”的开始和结束位置。本质上,它会匹配“spaghet”之后的“in”和“in”after“insert”,但不匹配“in”in “插入”。
在我当前的示例中,它将 return ((9, 10), (19, 20))。当然,“in”在这里只是一个占位符,因为在我的代码中它会被替换为有意义的字符串。任何帮助将不胜感激。
谢谢,蓝

一个班轮-

>>> import re
>>> [(m.start(0) + 1, m.end(0)) for m in re.finditer(r'\bin\b', 'spaghet in insert in impossible(banana)')]
[(9, 10), (19, 20)]

说明

我们将使用正则表达式 \bin\b 来匹配 in 个单词,您可以根据自己的喜好随意更改。

re.finditer returns 可迭代的 match objects, match objects have the convenient start and end 方法,用于提取每个匹配项的开始和结束索引(0 索引)。

您要求起始索引为 1 索引,因此 m.start(0) + 1,0 为完全匹配(无捕获组)