Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: Interactive search and replace with perl compatible regular expressions

Tags:

replace

vim

perl

According to this page you can use perl compatible regular expression with

:perldo s/pattern/insert/g.

This works fine.

But, how can I get interactive search and replace with PCRE syntax in vim?

Since this does not work with perldo I search for a different solution.

like image 363
guettli Avatar asked Sep 07 '15 08:09

guettli


People also ask

Does vim support regex?

Vim has several regex modes, one of which is very magic that's very similar to traditional regex. Just put \v in the front and you won't have to escape as much.

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

Is Python regex Perl Compatible?

Python supports essentially the same regular expression syntax as Perl, as far as the regular expressions themselves. However, the syntax for using regular expressions is substantially different. Regular expression support is not available out of the box; you must import the re module.


2 Answers

Till the current release version of vim, there is no way to do :s/[perlRegex]/bar/c

So you are asking for a feature that doesn't exist.

You can do matching with verymagic, however it is not Perl Regex compatible flag. It is still using the vimregex engine, just changed the way of escaping regex patterns.

For example, in perl, you can do lookahead/behind (?<=foo)..., (?=foo), (?!foo).., you can use the handy \K : som.*ing\Kwhatever etc, you cannot use those syntax in vim directly, no matter which 'magic' level you have set. Vim has the same feature, but different syntax:

\@=
\@!
\@<=

and also the \zs \ze are very handy, even more powerful than perl's \K.

Vim is an Editor, with vim regex, you can not only do text matching, but also match base on visual selection, cursor position and so on.

If you really need to do complex pattern matching and really need do them in vim, learn vim regex! It is not difficult for you if you "know pcre very well"

like image 137
Kent Avatar answered Sep 30 '22 15:09

Kent


Probably the closest you can get is:

:s/\vfoo/bar/gc
like image 27
Jonathan.Brink Avatar answered Sep 30 '22 16:09

Jonathan.Brink