1

I have this perl regex:

s/(^(#+)\s.*?\g2)/$1 =~ s|\n| |rg/gmse

It strips out all new lines between ##+ characters and replaces them with a space. It'll take a string like:

before text
more text
### hjh jh ja jhjasdhf jh'j
asdk kas dkjakdjf kasjd fkjasdkfj
kajsdkjf kasjdf end ###
after text

and change it to:

before text
more text
### hjh jh ja jhjasdhf jh'j asdk kas dkjakdjf kasjd fkjasdkfj kajsdkjf kasjdf end ###
after text

I want to do the same with vim. I discovered I can use \= to turn the right hand side into an expression, but how do I perform a substitution on the value of \1 and print it out?

%s/\v(^(#+)\s.*?\g2)/\= WHAT GOES HERE?/g

2
  • 3
    See :h submatch()
    – Matt
    Aug 24 '20 at 16:51
  • with a perl-embedded Vim, you can simply use :perldo ... might be faster to do it the perl way Aug 26 '20 at 12:16
2

You can use the substitute() function to do a text replacement on the replacement side of a :s command. And you can use submatch() to have access to the matched groups, including submatch(0) for the whole match.

You also need to use the correct Vim syntax for the regex, which differs from the Perl syntax in a few ways. You should use {-} instead of *? for a non-greedy repetition, \2 instead of \g2 to match the exact same string matched in group 2, and you also need \_. to match any character including newlines.

Actually, since you can use the full match, you don't need the outer capture group, so you can get rid of that set of parens too, and use \1 to match the sequence of #s.

Putting it all together:

:%s/\v^(#+)\s\_.{-}\1/\=substitute(submatch(0), '\n', ' ', 'g')/
4

Just in case you want to join lines and you only used regular expressions because it is the "natural" choice in Perl, there is another way in Vim. You can combine the :global and the :join command to join all lines between two sequences of hashes:

g/#\+/;/#\+/ join

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.