亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使 python re.sub 多次查看

使 python re.sub 多次查看

FFIVE 2023-06-06 17:18:52
假設我有以下代碼:s = 'cucumber apple tomato'def f(match):    if match.group(2) not in ('apple', ):        return '%s (%s)' % (match.group(1), match.group(2))    else:        return match.group()如何進行re.sub(r'([a-z])+\s+[a-z]+', f, s)輸出cucumber apple (tomato)?問題是正則表達式引擎只測試cucumber apple,而不是apple tomato。
查看完整描述

2 回答

?
慕的地8271018

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)']


查看完整回答
反對 回復 2023-06-06
?
慕神8447489

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 ”


查看完整回答
反對 回復 2023-06-06
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號