In Vim
, on a selection, the following
:'<,'>s/^\(\w\+ - \w\+\).*/\1/
or
:'<,'>s/\v^(\w+ - \w+).*/\1/
parses
Space - Commercial - Boeing
to
Space - Commercial
Similarly,
apple - banana - cake - donuts - eggs
is parsed to
apple - banana
Explanation
^
: match start of line
\
-escape (
, +
, )
per the first regex (accepted answer) -- or prepend with \v
(@ingo-karkat's answer)
\w\+
finds a word (\w
will find the first character): in this example, I search for a word followed by -
followed by another word)
.*
after the capturing group is needed to find / match / exclude the remaining text
Addendum. This is a bit off topic, but I would suggest that Vim is not well-suited for the execution of more complex regex expressions / captures. [I am doing something similar to the following, which is how I found this thread.]
In those instances, it is likely better to dump the lines to a text file and edit it "in place"
sed -i ...
or in a redirect
sed ... > out.txt
In a terminal (or BASH script, ...):
echo 'Space Sciences - Private Industry - Boeing' | sed -r 's/^((\w+ ){1,2}- (\w+ ){1,2}).*/\1/'
Space Sciences - Private Industry
cat in.txt
Space Sciences - Private Industry - Boeing
sed -r 's/^((\w+ ){1,2}- (\w+ ){1,2}).*/\1/' ~/in.txt > ~/out.txt
cat ~/out.txt
Space Sciences - Private Industry
## Caution: if you forget the > redirect, you'll edit your source.
## Subsequent > redirects also overwrite the output; use >> to append
## subsequent iterations to the output (preserving the previous output).
## To edit "in place" (`-i` argument/flag):
sed -i -r 's/^((\w+ ){1,2}- (\w+ ){1,2}).*/\1/' ~/in.txt
cat in.txt
Space Sciences - Private Industry
sed -r 's/^((\w+ ){1,2}- (\w+ ){1,2}).*/\1/'
(note the {1,2}
) allows the flexibility of finding {x,y}
repetitions of a word(s) -- see https://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html .
Here, since my phrases are separated by -
, I can simply tweak those parameters to get what I want.
:%norm ay<CR>
. – Hepburnl
, enter Visual Block mode withCtrl+v
, mark whole column withShift+g
followed byl
, then enter Insert mode withShift+i
and input 'y'. 7 keystrokes including finishingEsc
to exit Insert mode. Not posting as an answer because it's not really about capture groups (which is what I searched for when I found this). :-) – Starter