re.sub 方法不适用于'$'模式



我试图用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'ands*$'
f_value = re.sub(regex,'',fvalue)
print(f_value)

我删除了捕获组,因为您没有使用它,取消了$锚点的转义,并插入了可能的空格 (s*(。

最后,打印结果f_value而不是输入fvalue

最新更新