Why doesn't vim accept \? in substitute()?

Viewed 103
:echo substitute("15", "15\?", "replaced", "")
15

:help substitute() reports that we are cpoptions is empty and we're using magic and some other small differences (that don't seem to point to \? not working).

A file with the following:

15

followed by

:%s/\m15\?/replaced/

will indeed replace the 15 with replaced.

Can anybody point out to me the divergence here and where the manual explains this?

1 Answers

Try

:echo substitute("15", "15\\?", "replaced", "")

In double quotes, \ is interpreted. For example, "\n" is the newline, "\\" is the backslash character \, etc. As the expression "\?" does not have a special interpretation, it just becomes a question mark ?, and therefore you are in effect providing the regex 15? to the function. So you need to escape \ in order to make the string be recognized as \? by Vim.

Alternatively, you can use single quotes ("literal-string"), which does not interpret but takes \ as is:

:echo substitute("15", '15\?', "replaced", "")

(To see the difference, try echo "\?" and echo '\?'.)

Some relevant help entries are :help expr-" and :help expr-'

Related