[英]How to search for a word and then replace text after it using regular expressions in python?
[英]Python , regular expressions, replace text containing a word
我想替換所有包含給定單詞的文本(例如:'mama')。 我用下面的代碼:
import re
text1 = 'I love mama so much'
result = re.sub(r"\bmama\b",'Nice', text1)
print (result)
結果是:“我非常愛尼斯”,但是我希望它只是“不錯”。
我怎樣才能做到這一點 ? 謝謝。
如果您不是特別在尋找正則表達式解決方案,則可以這樣做(我假設它不包含“媽媽”,您想返回原始短語嗎?):
result = 'Nice' if 'mama' in text1 else text1
這就是re.sub的作用。 如果要替換整個字符串(使用正則表達式),請執行
text1 = 'I love mama so much'
if re.search(r' mama ', text1):
text1 = 'Nice'
您可以將正則表達式字符串包裝在通配符中。
result = re.sub(r".*\bmama\b.*",'Nice', text1)
。 代表任何字符,*代表字符左側0+個字符。
如果您希望結果為“ Nice”,
result = 'Nice'
如果表達式中必須有“ Nice”的額外條件,請添加一個if語句
if 'mama' in text1:
result = 'Nice';
您需要使用
import re
text1 = 'I love mama so much'
result = 'Nice' if re.search(r"\bmama\b", text1) else text1
print(result)
'Nice' if re.search(r"\\bmama\\b", text1) else text1
行表示,如果text1
整個單詞的正則表達式匹配mama
,則result
應等於Nice
,否則,結果為應該等於text1
。
請注意, re.search
會在字符串中的任何位置搜索匹配項,而re.match
只會在字符串的開頭查找匹配項。
是基本情況
您可以按以下方式使用此代碼
import re
text1 = 'I love mama so much'
result = re.sub(r"m..a",'Nice', text1)
print(result)
它可以在基本情況下為您提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.