简体   繁体   English

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

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

Am trying to replace 'and' at the end of the string with re.sub method.我试图用 re.sub 方法替换字符串末尾的“and”。 But either all the 'and' are getting changed or nothing is getting changed.但是,要么所有的“和”都变了,要么什么都没有变。 I need to replace and only at the end.我需要更换并且只在最后。

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

Output输出

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

You have a couple of problems with your code.您的代码有几个问题。 First, you're printing the input, not the output.首先,您打印的是输入,而不是输出。 But also, you're escaping the $ as pointed out in the comments, and you have whitespace after the "and" in the input but before the end of the string, so (and$) will not match either.而且,您正在转义注释中指出的$ ,并且在输入中的“and”之后但在字符串末尾之前有空格,因此(and$)也不会匹配。

Try something like this:尝试这样的事情:

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

I removed the capture group, since you're not using it, unescaped the $ anchor, and inserted possible whitespace ( \\s* ).我删除了捕获组,因为您没有使用它,对$锚点进行转义,并插入了可能的空格 ( \\s* )。

And finally, print the result f_value instead of the input fvalue .最后,打印结果f_value而不是输入fvalue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM