Search code examples
regexvariablesneovimone-liner

nvim - return a portion of the matched pattern (capture group)?


Data:

line 1 = 1232
line 2 == 1456
line 3=2345

Expected output

line 1=1232
line 2==1456
line 3=2345

This is in a editor & I want to remove the spaces as mentioned above. I want to use something like this:

:'<,'>s/ =+ /variable that returns the matched pattern except spaces/g

Is there any 'variable that returns the matched pattern. except spaces' in nvim or vim that I can use to achieve this with the one-liner?

Thanks in advance!


Solution

  • You can use a capture group to capture 1 or more times an equals sign.

    It is not called a variable, but you use a backreference \1 in the replacement, that holds the matched value of capture group 1.

    The capture group is denoted with the escaped parenthesis, and the quantifier for 1 or more times is the escaped plus sign.

    In vim:

    :'<,'>s/ \(=\+\) /\1/g
    

    According to the comments, in nvim without the escapes:

    :'<,'>s/ (=+) /\1/g