2 回答

TA貢獻1796條經驗 獲得超4個贊
使用捕獲前瞻:
>>> s = 'cucumber apple tomato'
>>> re.findall(r'(\w+)(?=[ \t]+(\w+))', s)
[('cucumber', 'apple'), ('apple', 'tomato')]
這使您可以在不消耗字符串的情況下捕獲第一個單詞前面的第二個單詞。
你可以變成(我>>認為<<)是你想要的結果:
>>> [f'{t[0]} ({t[1]})' if t[1]=='apple' else t for t in re.findall(r'(\w+)(?=[ \t]+(\w+))', s)]
['cucumber (apple)', ('apple', 'tomato')]
在您的評論中,您有一個不同的示例和不同的答案模式。對于該結果,只需使用可選匹配項:
>>> s='cucumber apple tomato tomato apple cucumber tomato tomato'
>>> [f'{t[0]} {t[1]} ({t[2]})' if t[2] else f'{t[0]} ({t[1]})' for t in re.findall(r'(\w+)(?:[ \t]+(\w+))?(?:[ \t]+(\w+))?', s)]
['cucumber apple (tomato)', 'tomato apple (cucumber)', 'tomato (tomato)']

TA貢獻1780條經驗 獲得超1個贊
這是基于您在評論中提供的信息,因此可能不完全是您要查找的信息,但是:
可以有任意數量的單詞:'cucumber apple tomato tomato apple cucumber tomato tomato' 輸出應該是 'cucumber apple (tomato) tomato apple (cucumber) tomato (tomato)'
此正則表達式將捕獲“apple”之后和行尾之前的所有非空格字符,同時忽略以“apple”結尾的單詞并允許它成為行中的第一個。
(?:^| )apple ([^ ]*)|([^ ]+)$
對于示例字符串
“apple cucumber pineapple tomato tomato apple cucumber tomato tomato”,
它將選擇
“apple cucumber pineapple tomato tomato apple cucumber tomato tomato ”
添加回答
舉報