[英]python regex finding all the first starting words of a string that are in a list
提供了一個單詞列表,我想在字符串的開頭獲取屬於該列表的字符串的所有單詞列表。
p=['horse','pig','cow']
f="cow horse this"
joinit = '\s*|'.join(p)
rex = rf"^({joinit})(({joinit})*)?"
print(rex)
matches = re.search(rex,f)
matches
解釋:我嘗試用 ^ 獲取第一個詞,然后匹配任意數量的所有其他詞。
這不起作用,因為我希望提取“牛馬”,但我只得到“牛”
一些想法?
嘗試( regex101 ):
import re
p = ["horse", "pig", "cow"]
f = "cow horse this"
pat = "|".join(map(re.escape, p))
pat = re.compile(fr"(?:\s*(?:{pat})\b)+")
print(pat.match(f).group(0))
印刷:
cow horse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.