Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim search replace regex

Tags:

regex

replace

vim

I'm trying to replace all occurrence of hello(...) by hello[...]

I tried things like %s/hello\((.*?)\)/hello\[$1\]/ without any success

Any help pls ?

like image 826
Jason Lince Avatar asked May 02 '12 05:05

Jason Lince


People also ask

Does vim search support regex?

Using Regex in VimMany of Vim's search features allow you to use regular expressions. Some of them are: The search commands ( / and ? ) The global and substitute command-line (ex) commands ( :g and :s )

How do I search and replace in vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.


1 Answers

That's Perl syntax, not Vim. In Vim regular expressions, at least by default, parentheses match themselves and backslashed parentheses capture - the opposite of Perl. Also, Vim doesn't understand the non-greedy modifier ?, and capture groups are interpolated with \n, not $n. Try this:

%s/hello(\([^)]*\))/hello[\1]/

Alternatively, you can use the \v ("very magic") modifier to make the behavior with respect to special characters and backslashes more Perl-like, though it doesn't make Vim understand *? or change its interpolation syntax:

%s/\vhello\(([^)]*)\)/hello[\1]/

Also, note that you don't need backslashes on the square brackets in the replacement text - the right hand side of a substitution command is not a regular expression, so you don't have to worry about most of the characters that are special in one. Pretty much only the backslash itself is special, and can be used to include capture groups or a literal instance of itself or the delimiter.

like image 51
Mark Reed Avatar answered Sep 28 '22 22:09

Mark Reed