Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between vim regex and normal regex?

Tags:

regex

linux

vim

I noticed that vim's substitute regex is a bit different from other regexp. What's the difference between them?

like image 275
guilin 桂林 Avatar asked Oct 05 '10 14:10

guilin 桂林


People also ask

What type of regex does Vim use?

vim has a mixed up regex syntax.

Are there different types of regex?

There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression.

Why you should not use regex?

Regex isn't suited to parse HTML because HTML isn't a regular language. Regex probably won't be the tool to reach for when parsing source code. There are better tools to create tokenized outputs. I would avoid parsing a URL's path and query parameters with regex.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.


1 Answers

"Regular expression" really defines algorithms, not a syntax. What that means is that different flavours of regular expressions will use different characters to mean the same thing; or they'll prefix some special characters with backslashes where others don't. They'll typically still work in the same way.

Once upon a time, POSIX defined the Basic Regular Expression syntax (BRE), which Vim largely follows. Very soon afterwards, an Extended Regular Expression (ERE) syntax proposal was also released. The main difference between the two is that BRE tends to treat more characters as literals - an "a" is an "a", but also a "(" is a "(", not a special character - and so involves more backslashes to give them "special" meaning.

The discussion of complex differences between Vim and Perl on a separate comment here is useful, but it's also worth mentioning a few of the simpler ways in which Vim regexes differ from the "accepted" norm (by which you probably mean Perl.) As mentioned above, they mostly differ in their use of a preceding backslash.

Here are some obvious examples:

 Perl    Vim     Explanation --------------------------- x?      x\=     Match 0 or 1 of x x+      x\+     Match 1 or more of x (xyz)   \(xyz\) Use brackets to group matches x{n,m}  x\{n,m} Match n to m of x x*?     x\{-}   Match 0 or 1 of x, non-greedy x+?     x\{-1,} Match 1 or more of x, non-greedy \b      \< \>   Word boundaries $n      \n      Backreferences for previously grouped matches 

That gives you a flavour of the most important differences. But if you're doing anything more complicated than the basics, I suggest you always assume that Vim-regex is going to be different from Perl-regex or Javascript-regex and consult something like the Vim Regex website.

like image 120
J-P Avatar answered Sep 18 '22 14:09

J-P