簡體   English   中英

re.sub 方法不適用於“$”模式

[英]re.sub method not working with '$' pattern

我試圖用 re.sub 方法替換字符串末尾的“and”。 但是,要么所有的“和”都變了,要么什么都沒有變。 我需要更換並且只在最后。

fvalue = "$filter = Name eq 'abc' and Address eq 'xyz' and "
regex = r'(and\$)'
f_value = re.sub(regex,'',fvalue)
print(fvalue)

輸出

$filter = Name eq 'abc' and Address eq 'xyz' and

您的代碼有幾個問題。 首先,您打印的是輸入,而不是輸出。 而且,您正在轉義注釋中指出的$ ,並且在輸入中的“and”之后但在字符串末尾之前有空格,因此(and$)也不會匹配。

嘗試這樣的事情:

fvalue = "$filter = Name eq 'abc' and Address eq 'xyz' and "
regex = r'and\s*$'
f_value = re.sub(regex,'',fvalue)
print(f_value)

我刪除了捕獲組,因為您沒有使用它,對$錨點進行轉義,並插入了可能的空格 ( \\s* )。

最后,打印結果f_value而不是輸入fvalue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM