Falassion
Falassion

Reputation: 741

Vim Search/replace: what do I need to escape?

I'm trying to search and replace $data['user'] for $data['sessionUser'].

However, no matter what search string I use, I always get a "pattern not found" as the result of it.

So, what would be the correct search string? Do I need to escape any of these characters? :%s/$data['user']/$data['sessionUser']/g

Upvotes: 17

Views: 8538

Answers (5)

Paul Chris Jones
Paul Chris Jones

Reputation: 2909

Here's a list of all special search characters you need to escape in Vim:

`^$.*[~)+/\

Upvotes: 12

cppcoder
cppcoder

Reputation: 23095

:%s/\$data\[\'user\'\]/$data['sessionUser']/g

I did not test this, but I guess it should work.

Upvotes: 9

1983
1983

Reputation: 5963

There's nothing wrong with with the answers given, but you can do this:

:%s/$data\['\zsuser\ze']/sessionUser/g

\zs and \ze can be used to delimit the part of the match that is affected by the replacement. You don't need to escape the $ since it's the at the start of the pattern and can't match an EOL here. And you don't need to escape the ] since it doesn't have a matching starting [. However there's certainly no harm in escaping these characters if you can't remember all the rules. See :help pattern.txt for the full details, but don't try to digest it all in one go!

If you want to get fancy, you can do:

:%s/$data\['\zsuser\ze']/session\u&/g

& refers to the entire matched text (delimited by \zs and \ze if present), so it becomes 'user' in this case. The \u when used in a replacement string makes the next character upper-case. I hope this helps.

Upvotes: 4

Lee Netherton
Lee Netherton

Reputation: 22482

Search and replace in vim is almost identical to sed, so use the same escapes as you would with that:

:%s/\$data\['user'\]/$data['session']/g

Note that you only really need to escape special characters in the search part (the part between the first set of //s). The only character you need to escape in the replace part is the escape character \ itself (which you're not using here).

Upvotes: 4

lucapette
lucapette

Reputation: 20724

The [ char has a meaning in regex. It stands for character ranges. The $ char has a meaning too. It stands for end-line anchor. So you have to escape a lot of things. I suggest you to try a little plugin like this or this one and use a visual search.

Upvotes: 1

Related Questions