非常好!在选择中,使用以下内容(例如):
:'<,'>s/^\(\w\+ - \w\+\).*/\1/
或
:'<,'>s/\v^(\w+ - \w+).*/\1/
将Space - Commercial - Boeing 解析为Space - Commercial。
解释:
-
^ : 匹配行首
-
\-escape (, +, ) 每个第一个正则表达式(接受的答案) - 或前面加上 \v(@ingo-karkat 的答案)
-
\w\+ 找到一个词(\w 将找到第一个字符):在这个例子中,我搜索一个词,然后是 -,然后是另一个词)
-
.* 捕获组后需要查找/匹配/排除剩余文本
附录。 这有点离题,但我建议 Vim 不适合执行更复杂的正则表达式/捕获。 [我正在做类似于以下的事情,这就是我找到这个线程的方式。]
在这些情况下,最好将这些行转储到文本文件并“就地”编辑 (sed -i ...) 或重定向 (sed ... > out.txt)。
echo 'Space Sciences - Private Industry - Boeing' | sed -r 's/^((\w+ ){1,2}- (\w+ ){1,2}).*/\1/'
Space Sciences - Private Industry
touch ~/in.txt
touch ~/out.txt
echo 'Space Sciences - Private Industry - Boeing' > ~/in.txt
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.
## source unaltered:
cat in.txt
Space Sciences - Private Industry - Boeing
## edit in place:
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/' 允许灵活地查找单词的{x,y} 重复项——参见https://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html。在这里,由于我的短语由- 分隔,我可以简单地调整这些参数以获得我想要的。