lor*_*age 1 vim text-processing regular-expression
我有一个大文件,其中包含以下形式的多行:
USet07-1
USet07-2
USet08-1
USet08-2
.
.
.
USet22-2
.
.
.
Run Code Online (Sandbox Code Playgroud)
我想-从 中的这些字符串中删除连字符/破折号vim。我用以下命令搜索字符串:
:/USet\d\d-\d
Run Code Online (Sandbox Code Playgroud)
但是当我尝试用它们替换这些时
:%s/Uset\d\d-\d/USet\d\d\d
Run Code Online (Sandbox Code Playgroud)
我显然明白了
USetddd
Run Code Online (Sandbox Code Playgroud)
对于所有实例。但我想要的是:
USet071
USet072
USet081
USet082
.
.
.
USet222
.
.
.
Run Code Online (Sandbox Code Playgroud)
如何才能做到这一点?我可以重用部分匹配字符串并将其用于替换吗?
是的,您可以使用捕获组。基本上,您可以使用以下内容包装模式的各个部分,\(...\)并使用以下内容在替换部分中引用该部分\1:
:%s/Uset\(\d\d\)-\(\d\)/USet\1\2
Run Code Online (Sandbox Code Playgroud)
Since you only want to remove a single part of the pattern, a shorter option is restricting the actual match (but still asserting that the stuff around is also there) via \zs (match start) and \ze (match end):
:%s/Uset\d\d\zs-\ze\d//
Run Code Online (Sandbox Code Playgroud)
These are all very basic things, and capture groups are common in many regular expression-based tools (like sed). Learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.
| 归档时间: |
|
| 查看次数: |
5330 次 |
| 最近记录: |