首页 > 解决方案 > 如何使用正则表达式从迭代器中获得完全匹配?

问题描述

我已经使用 + 和 $ 来标记单词的开头和结尾,但我不知道如何将其放入编译中而不会出现语法错误。不断发生的是匹配也会找到更大的单词,我只想要完全匹配。

>>> mumu = ["act", "magic", "lose", "dance"]
>>> matcher = ["That is a terrible actor", "This is the first act", "It works like magic", "That's because he is a magician", "Don't be afraid to lose", "Don't be a loser", "Try this dance", "It won't make you a dancer"]
> 
> >>> def intermediate(first, second):
...     dul = len(second)
...     milly = cycle(second)
...     for y in range(dul):
...         t = re.compile(next(milly))
...         for i in first:
...             print(t)
...             if re.search(t, i) != None:
...                 print(i)
...                 dul -= 1
...                 continue
...             else:
...                 print("try again")
...                 dul -= 1
...                 continue
...         continue

结果是

re.compile('act')
That is a terrible actor
re.compile('act')
This is the first act

标签: pythonpython-3.xregexiteratorgenerator

解决方案


推荐阅读