In vim I want to find a string and insert spaces i

2019-04-08 10:36发布

问题:

I have been trying to search and replace with regex and capture groups in a simple way, but have no idea how.

Let's say I want to operate on the previous sentence capturing "trying" and replacing with "t r y i n g".

:%s/\vtrying{-}/ \1/g

回答1:

You have a solution, but here is a different one:

 %s/trying/\=join(split(submatch(0),'\zs'), ' ')/g

That should be a little bit faster than the substitute() call, not that this matters much.



回答2:

Just do two substitute matches. Where the second one uses the substitute with an expression (\= at the beginning of the replacement :h sub-replace-expression)

:%s/trying/\=substitute(submatch(0), '\w\zs\ze\w', ' ', 'g')/

The expression just inserts a space between every word character.



回答3:

I have been trying to search and replace with regex and capture groups in a simple way, but have no idea how.

Let's say I want to operate on the previous sentence capturing "trying" and replacing with "t r y i n g".

:g~trying~exe "norm /trying^Mve^[" | s/\%V\(.\)/\1 /g

(Where the ^M is entered by CTRL-Q Enter, and ^[ is CTRL-Q Esc)

I have been t r y i n g to search and replace with regex and capture groups in a simple way, but have no idea how.

Let's say I want to operate on the previous sentence capturing "t r y i n g " and replacing with "t r y i n g".

NB this will, I think, only work for one instance of 'trying' on a line.

The g global command matches lines with 'trying' in them, then runs 'execute' with the 'normal' command to jump to it, visually select it, then the | separates another command, which does a search and replace of any character within the \%V visual selection, with the character and a space.

It also adds a space at the end.

All in all, it's not as good as @FDinoff's answer.