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

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

如何在正則表達式匹配后使用正則表達式刪除特定文本部分

如何在正則表達式匹配后使用正則表達式刪除特定文本部分

www說 2022-06-14 15:06:31
假設我有這個列表:names = ['your name', 'the name', 'his name', 'her name', 'their name', 'employer name', "employer's name", "father's name",        "mother's name", "maiden name", "son's name", "daughter's name", "brother's name", "sister's name"]假設我有這段文字:text = "What is your name?  Well,  uh it's John Smith.  Thanks for asking. Anyway, I'd doing well."如何使用正則表達式在文本中查找列表名稱的每個元素,并立即用“[name]”替換元素之后的文本塊(例如,長度為 50)。所以我的輸出是:text = "What is your name [name] Anyway, I'd doing well."到目前為止,我在下面有這段代碼,但它只用“[name]”替換了元素,而不是元素后面的實際文本。def my_replace3(match):    match = match.group()    return " [name] "def no_name(text):    names = ['your name', 'the name', 'his name', 'her name', 'their name', 'employer name', "employer's name", "father's name",        "mother's name", "maiden name", "son's name", "daughter's name", "brother's name", "sister's name"]    regex = re.compile(r'\b(' + '|'.join(names) + r')\b', re.IGNORECASE)    text = re.sub(regex, my_replace3, text)    return text我不是一個偉大的正則表達式專家,所以你的幫助將不勝感激。
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

如果要在匹配后替換 50 個字符,請添加.{50}到正則表達式。


然后在替換字符串中使用反向引用將匹配的字符串復制到替換。


def no_name(text):

    names = ['your name', 'the name', 'his name', 'her name', 'their name', 'employer name', "employer's name", "father's name",

        "mother's name", "maiden name", "son's name", "daughter's name", "brother's name", "sister's name"]

    regex = re.compile(r'\b(' + '|'.join(map(re.escape, names)) + r')\b.{50}', re.IGNORECASE)

    text = re.sub(regex, r'\1 [name]', text)

    return text

您還應該re.escape()在將應該完全匹配的字符串插入到正則表達式中時使用,以防它們中的任何一個包含正則表達式運算符。


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 423 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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