tags:

views:

668

answers:

3

If I want all the lines with the text 'ruby' but not 'myruby' then this is what I would do.

:g/\<ruby\>/

My question is what is the meaning of lesser than and greater than symbol here? The only regular expression I have used is while programming in ruby.

Similarly if I want to find three consecutive blank lines then this is what I would do

/^\n\{3}

My question is why I am escaping the first curly brace ( opening curly brace ) but not escaping the second curly brace ( closing curly brace )?

+11  A: 

the \< and \> mean word boundaries. In Perl, grep and less (to name 3 OTOH) you use \b for this, so I imagine it's the same in Ruby.

Regarding your 2nd question, the escape is needed for the whole expression {3}. You're not escaping each curly brace, but rather the whole thing together.

See this question for more.

Nathan Fellman
A: 

For your first regular expression, you could also do:

:g/[^\ ]ruby\ /

This would ensure there was a space before and after your ruby keyword.

samoz
but that wouldn't match `ruby` at the beginning or end of a line.
Nathan Fellman
@Nathan Good point...
samoz
nor ' a beautiful ruby.', nor 'stole this ruby, then'...
Adriano Varoli Piazza
+3  A: 

Vim's rules for backslash-escaping in regexes are not consistent. You have to escape the opening brace of\{...}, but [...] requires no escaping at all, and a capture group is \(...\) (escaping both open and close paren). There are other inconsistencies as well.

Thankfully Vim lets you change this behavior, even on a regex-by-regex basis, via the magic settings. If you put \v at the beginning of a regex, the escaping rules become more consistent; everything is "magic" except numbers, letters, and underscores, so you don't need backslashes unless you want to insert a literal character other than those.

Your first example then becomes :g/\v<ruby>/ and your second example becomes /\v^\n{3}. See :h /magic and :h /\v for more information.

Brian Carper
You can 'set magic' n your vimrc to always have magic mode.By the way I think that a 'magic' expression is beginned by \m and not by \v\v means 'no magic'
Oli