Select all matching text in Vim?
Solution 1
This can be simply achieved, by running a :s
command with the n
flag set (which basically says, to not replace anything (but by using an \=
in the replace part, you can still capture the matches (see :h sub-replace-special
). So first let's clear register A:
qaq
Then you can capture your maches into register a by using:
:%s/'user': '[a-Z]*'/\=setreg('A', submatch(0), 'V')/gn
And paste your matches:
:put A
This needs at least Vim 7.4 (I forgot the actual patch number).
Solution 2
" clear the 'a' register
qaq
" global search and yank all lines ('A') into the 'a' register.
:g/'user': '[a-Z]*'/y A
Modify the part between :g/ and /y A
as needed.
" paste into another file
"aP
Related videos on Youtube
Marcus Buffett
Updated on September 18, 2022Comments
-
Marcus Buffett over 1 year
I have a bunch of data, and I want to yank everything that matches the following regex to a register :
/'user': '[a-Z]*'
Is there any way to copy all the matches to a register in vanilla vim? I've looked at this question, but it only works for one result, after pressing 'n' to go to the next result, it will use '//e' again and go to the end of the next result, instead of the beginning.
I've also looked at this SO question. It's almost exactly what I'm looking for, except I can't figure out how to change it to work with particular matches instead of the lines they are on.
-
evilsoup over 9 yearsIs there ever more than one match per line?
-
Marcus Buffett over 9 yearsYes, multiple matches per line
-
-
evilsoup over 9 yearsThis puts each match on its own line, which is useful behavior most of the time. Being a single ex-mode command, it'll also be faster than my macro for really large files. +1.
-
Christian Brabandt over 9 yearsWell, you can of course capture it in a list and then later do whatever you want with that. That was just an example since the OP did want to capture it in a register.
-
Marcus Buffett over 9 yearsThe data is all on one line
-
broomdodger over 9 yearsThere should be one line per line found. If there are multiple instances of the found string per line, then both will be listed in the same output line.
-
Marcus Buffett over 9 yearsI mean, the text, all the data, is just one line, wouldnt this just yank that one line?
-
broomdodger over 9 yearsYes, I did not know your data was one long line.
-
hhh over 6 yearsDoes this plugin really works? A lot of errors with the command
%YankMatches /re.sub([^)]*)/
-
Ingo Karkat over 6 years@hhh: You also need to install my ingo-library plugin. It's listed as a DEPENDENCY in the plugin's INSTALLATION section.
-
TankorSmash over 4 yearsI think this needs to be changed to
[a-zA-Z]
, at least on vim 8.1, otherwise vim says something about reverse character in range. -
Christian Brabandt over 4 years@TankorSmash this might depend on the locale