Regex to match beginning and end of line in Vim (quote around whole line)

13,867

Solution 1

How about:

:%s/.*/'&'/

"Replace zero or more characters with those characters preceded and succeded by a single-quote".

Solution 2

^ and $ do not hold those meanings (start or end of line) inside [ ], which is used for selecting a group of characters. Inside [ ], most regex operators lose their meaning (and some characters gain special meaning, or get a different meaning). A leading ^ in [] means that the group is negated - match everything except these characters. So [^$] matches on any character other than $. (And [$^] matches just the $ and ^ characters.)

If you want to match the start or end of a line, use /^\|$/, where | is or (needs to be escaped in Vim's default regex mode).

So:

:%s/^\|$/'/g

The g is needed since the ^ and $ are two independent matches, and s by default only acts on the first match in a line.

Solution 3

You don't really need to match the beginning and end of the line if you can just greedily match the whole thing:

:%s/\(.*\)/'\1'/

The main thing to know is to escape the parenthesis to create the "capture group", then use \1 to refer back to what was captured.

Solution 4

With norm[al] command and A to append control, I to prepend control which we make the :exe[cute] command to execute the second prepend 'norm' since by default :norm[al]command cannot be followed by another command as in :help :normal documented.

so the command would be as below:

:exe "%norm A'" |%norm I'

Note that % here performing the changes on all lines.

Share:
13,867

Related videos on Youtube

user1717828
Author by

user1717828

Updated on September 18, 2022

Comments

  • user1717828
    user1717828 over 1 year

    For an initial file with lines like this example:

    1
    12
    123
    1234
    12345
    

    The desired state of the file is

    '1'
    '12'
    '123'
    '1234'
    '12345'
    

    I've been doing this with two commands, :%s/^/'/g and :%s/$/'/g, that I would like to get into one. However, when I try

    :%s/[$^]/'/g
    

    I get the error

    E486: Pattern not found: [$^]
    

    I know the leading ^ in brackets means exclusion, so I figured putting $ first would mean match both the beginning and end of lines, which is obviously not happening.

    How can I match both the beginning and end of lines in vim?

  • user1717828
    user1717828 almost 7 years
    Neat option. Not exactly a regex but it gets the job done in vim.
  • user1717828
    user1717828 about 6 years
    Seems like a harder version of the accepted answer's %s/.*/'&'/g but maybe more extensible if there are several matching groups.