我有一定的串fruits
這樣:附加到行
Apples
Bananas
Pineapples
有一個在每一行的末尾的回車\r
,以及在開始和結束字符串。使用正則表達式,我將如何去追加: 1
到第一行Apples
的結尾?我曾嘗試以下無濟於事:
re.sub("Apples(\r)", "\1:1", fruits)
我的想法是,\1
應該更換什麼是在括號(\r)
,但一切都在模式所取代。
我有一定的串fruits
這樣:附加到行
Apples
Bananas
Pineapples
有一個在每一行的末尾的回車\r
,以及在開始和結束字符串。使用正則表達式,我將如何去追加: 1
到第一行Apples
的結尾?我曾嘗試以下無濟於事:
re.sub("Apples(\r)", "\1:1", fruits)
我的想法是,\1
應該更換什麼是在括號(\r)
,但一切都在模式所取代。
您正在做的是匹配"Apples\r"
,在此過程中捕獲"\r"
,然後用"\r:1"
替換整個匹配。
對於這個簡單的例子,不需要捕獲匹配到\r
,無論如何,因爲唯一能匹配它的是\r
。您可以將其硬編碼到替換字符串中。
我假設你想得到的字符串是"\rApples: 1\rBananas\rPineapples\r
。
您可以使用一個lookbehind使Apples
沒有被消耗(雖然我聽說,每天食用一個遠離醫生):
re.sub("(?<=Apples)\r", ": 1\r", fruits)
但你也可能只是這樣做:
re.sub("Apples\r", "Apples: 1\r", fruits)
如果您想在每個水果後添加: 1
,那麼後向將更加有用:
re.sub("(?<=[^\r])\r", ": 1\r", fruits)
上面說的是找到每個\r
,它跟隨的字符不是\r
,而是用: 1\r
替換它們。那麼結果將是:
# \rApples: 1\rBananas: 1\rPineapples: 1\r\r
如果你
re.sub("A(B)", "\1C", "AB")
你會得到BC
,因爲\1
是由什麼是在支架更換。
要獲得AC
,你應該做的:
re.sub("(A)B", "\1C", "AB")
有\ R作爲你的水果分離使得很難打印出來的東西;所以爲了這個答案的目的,我將在它的位置使用@字符。如果您將\ r分配給我的分隔符變量並使用實際的\ r分隔字符串作爲fruit_str,則後面的代碼工作原理相同。
一些解釋遵循代碼。
import re
def updateFruitQuantity(the_fruit, the_quantity, fruit_str, separator):
re_1 = r"(" + the_fruit + r")(:.*?|)" + separator
re_2 = r'\1:' + str(the_quantity) + separator
fruit_str = re.sub(re_1, re_2, fruit_str)
return(fruit_str)
separator = "@"
fruit_str = "@[email protected]@[email protected]"
print(fruit_str)
fruit_str = updateFruitQuantity("Pineapples", 25, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Bananas", 17, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Pineapples", 3, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Apples", 94, fruit_str, separator)
print(fruit_str)
fruit_str = updateFruitQuantity("Apples", 102, fruit_str, separator)
print(fruit_str)
這裏是代碼的輸出:
@[email protected]@[email protected]
@[email protected]@Pineapples:[email protected]
@[email protected]:[email protected]:[email protected]
@[email protected]:[email protected]:[email protected]
@Apples:[email protected]:[email protected]:[email protected]
@Apples:[email protected]:[email protected]:[email protected]
我要建立單獨的正則表達式的目標文本和替換文本。
這些目標表達式假定每個fruit:quantity後面跟着分隔符。目標表達式中有兩個捕獲組 - 每個都被括號包圍。第二個分組在目標表達式中非常重要,因爲它可以清除任何可能存在的數量元素。
替換表達式以\ 1開頭,代表與目標表達式中第一個分組相匹配的文本(例如「Apples」)。接下來是冒號,然後是要使用的數量字符串。這樣做可以確保任何現有的:數量可以用新數量正確替換,並且在沒有現有數量的情況下也可以使用。因此,例如,在我們的第三次更改中,您看到菠蘿的數量從25回到3.
隨着時間的推移,您需要另一種機制爲fruit_str添加新的水果類型。