Reputation: 865
I know that I can yank all matched lines into register A like this:
:g/regex/y/A
But I can't seem to figure out how to yank match regex groups into register A:
:g/\(regex\)/\1y A
(E10: \ should be followed by /, ? or &)
Upvotes: 18
Views: 5746
Reputation: 71
I like this solution, it also places a newline in-between each match:
:let @a='' | %s/regex/\=setreg('A', submatch(0) . "\n")/n
Upvotes: 3
Reputation: 1
Wouldn't work for me with the /n
flag - got nothing in the register - and without it vim did the substitute on the line.
Ended up with:
:g/pat1/s~pat2\\(regex\\)pat3~\=submatch(0).setreg('a',submatch(1))~
which seemed to do what I wanted.
Upvotes: 0
Reputation: 7150
You can also yank all matched line between two sessions to pointed register.
By way of example:
:11,21s/regex/\=setreg('A', submatch(0))/n
Matches regrex group from line 11 to line 21 rather than the whole file.
:/^ab/,/^cd/s/regex/\=setreg('A', submatch(0))/n
Matches regrex group from the line that stards with ab
to line with cd
.
More about session: http://vimregex.com/
Upvotes: 0
Reputation: 172758
If you just want to grab one part of the match, you can work with \zs
and \ze
. You need capture groups only for multiple parts, or reordering.
My ExtractMatches plugin provides (among others) a convenient :YankMatches
command that also supports replacements:
:[range]YankMatches[!] /{pattern}/{replacement}/[x]
Upvotes: 0
Reputation: 31459
You can do this with a substitute command.
:%s/regex/\=setreg('A', submatch(0))/n
This will append register a to whatever the regex matched. The n
flag will run the command in a sandbox so nothing will actually get replaced but the side effects of the statement will happen.
You probably want to empty the register first with
:let @a=''
Upvotes: 21