开发者

How to align the functionality of SUBSTITUTE() to the that of Vim's :substitute command for a given regex?

开发者 https://www.devze.com 2023-02-20 21:05 出处:网络
I am trying to deconstruct why this does not work in my (g)Vim console: :echo substitute(\"2321||aaaa|vvvv|334|mmmmm\",\"\\([0-9]\\+\\)\\(||.*\\)$\",\"\\1\",\"g\")

I am trying to deconstruct why this does not work in my (g)Vim console:

:echo substitute("2321||aaaa|vvvv|334|mmmmm","\([0-9]\+\)\(||.*\)$","\1","g")

... but when the cursor is on the line with the text 2321||aaaa|vvvv|334|mmmmm, the analogous command .s/\([0-9]\+\)\(||.*\)$/\1/g returns what I expect! (that is, it replaces the line with the text 2321)


I've narrowed it down to the following discrepancy, and would like to know how to get around it. I expect the command below to return ||aaaa|vvvv||mmmmm:

:echo substitute("2321||aaaa|vvvv|334|mmmmm","\([0-9]\)","","g")

Instead, it returns the unchanged version of the input 2321||aaaa|vvvv|334|mmmmm, which means the regex \([0-9]\) did not find a match. Removing the parenthesis, the command below does work:

:echo substitute("2321||aaaa|vvvv|334|mmmmm","[0-9]","","g")

It appears as if the SUBSTITUTE() function has severely limited regex capabilty when compared to the :substitute command. However, the documentation http://vimdoc.sourceforge.net/htmldoc/eval.html#substitute%28%29 does not mention this. Is there a workaround, or did I miss something that is menti开发者_开发技巧oned elsewhere?


(I'm running gVim on XP)

As an aside: Does the question as it is currently formulated add or take away from its clarity/usefulness? I could have also used the simpler but less informative title of 'Vim substitute question', in line with many other users of this forum?


Either use single quotes or escape backslashes

:echo substitute("2321||aaaa|vvvv|334|mmmmm",'\([0-9]\+\)\(||.*\)$','\1','g')

See :help expr-quote and :help literal-string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号