VIM Regular Expressions are the ugliest

PCRE is beautiful by comparison.

Here is a good reference:

http://www.geocities.com/volontir/#substitute

I wanted to basically Perl -pie ’s/_(\w+)/<\1>\0<\/\1>/’  It is kinda ugly, but it isn’t too bad if you know regex.

In VIM, the + modifier and the grouping parentheses require escaping as well, so it turned into this:

:’<,’>s/_\(\w\+\)/<\1>&<\/\1>/

WOW. The only things not prefixed with a backslash in that regex is _, <, >, and &.

My head would be spinning, but I’m too happy that I got VIM to do what I want.

3 Responses to “VIM Regular Expressions are the ugliest”

  1. Dane Says:

    Actually VIM is pretty flexible with regard to escaping things. In this case, I’d suggest you use turn on the ‘very magic’ switch (see :help magic for more information). With very magic turned on you could have typed:

    :’s/_\v(\w+)/&/

    *Almost* as concise as the perl equivelant (but not quite :) ).

  2. Dane Says:

    oops, it ate my characters - you get the idea though - by putting “\v” at the beginning of your search you are then no longer required to escape the +, (, and ) characters.

  3. RL Says:

    Want to break a long line of text into 80 character per line in Vim.

    %s/\(.\{80}\)/\1\r/g

    Explained:
    Group match: \( …. \)
    Match 80 characters: .\{80}
    Replace match with first group and carriage return: \1\r
    Do search replace global: %s/…./…../g

Leave a Reply