I would like to replace every instance of ...
with the string \ldots
, but both strings contain special characters. I have tried :%s/\<...\>/\ldots
but this searches for all three character words and seemingly replaces them with "dots". How can I do this correctly? Thanks.
2 Answers
I'm not positive as you're a little vague on the details, but I believe the problem stems from the fact that \l
is not interpreted literally. Use \\l
to get a literal \l
in this case.
In a search and replace a \l
will make the next character lowercase. To avoid this we escape the backslash with another backslash.
The second problem is that .
in regex stands for any character. So, in fact \<...\>
will search for any three character word as you've described. As Sato Katusura suggests, use \.\.\.
to get three dots.
Tumbler41's answer is a great explanation of why your approach doesn't work. Here's another solution:
Use the "magic" flag. This tells vim which characters should be treated as special and which ones should not. If you specify "Nomagic" with \V
, than only the backslash character will be special.
:%s/\V.../\\ldots/g
From :help magic
3. Magic */magic*
Some characters in the pattern are taken literally. They match with the same
character in the text. When preceded with a backslash however, these
characters get a special meaning.
Other characters have a special meaning without a backslash. They need to be
preceded with a backslash to match literally.
*/\v* */\V*
Use of "\v" means that in the pattern after it all ASCII characters except
'0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning. "very magic"
Use of "\V" means that in the pattern after it only the backslash and the
terminating character (/ or ?) has a special meaning. "very nomagic"
Examples:
after: \v \m \M \V matches
$ $ $ \$ matches end-of-line
. . \. \. matches any character
* * \* \* any number of the previous atom
~ ~ \~ \~ latest substitute string
() \(\) \(\) \(\) grouping into an atom
| \| \| \| separating alternatives
\a \a \a \a alphabetic character
\\ \\ \\ \\ literal backslash
\. \. . . literal dot
\{ { { { literal '{'
a a a a literal 'a'
%s/\.\.\./\\ldots/g
will replace all groups of three dots.