對於正則表達式來說很新,所以我不知道如何做到這一點。僅供參考我正在使用Python,但我不確定這有多重要。正則表達式找到匹配的字符串,然後刪除空間之間的所有內容
我想要做的是這樣的:
string1 = 'Metro boomin on production wow'
string2 = 'A loud boom idk why I chose this as an example'
pattern = 'boom'
result = re.sub(pattern, ' ____ ', string1)
result2 = re.sub(pattern, ' ____ ', string2)
現在這會給我"Metro ____in on production wow"
和"a loud ____ idk why I chose this as an example
我要的是既"Metro ______ on production wow"
和"a loud ____ idk why I chose this as an example"
基本上我想在另一個字符串中找到目標字符串,然後將該匹配字符串和2個空格之間的所有內容替換爲新字符串
有沒有辦法可以做到這一點?另外如果可能的話,最好在我的替換字符串中根據原始字符串的長度來設置可變長度。
使用含有'boom'一個詞相匹配的正則表達式。 – Barmar
使用@coldspeed答案,您應該能夠通過利用指定函數作爲're.sub'中的替換項的能力來調整替換的長度。看看're.sub'文檔。 – user1527491