简体   繁体   中英

How to ignore few characters in search and replace in vim editor

I want to do something like this in the vim editor:

:%s/SETR P:LL../SETR P:LH../g

There are multiple lines which start with SETR P: in my file where I want to replace the second L with an H while the remaining two letters in that line will be the same as it was before.

Say if it was earlier SETR P:LLHC
After replacing it would be SETR P:LHHC

Can I do it in one instruction with the vim editor?

This is commonly done with capture groups . Capture the part of the source pattern that you want to re-include in the replacement via \\(...\\) . Then, in the replacement, you can refer to that part via \\1 (and following via \\2 , and so on):

:%s/SETR P:LL\(..\)/SETR P:LH\1/g

This is documented under :help /\\( .


An alternative here would be to end the match after the LL , using \\ze (match end). The rest of the pattern ( .. ) is still checked, but it is not part of the match.

:%s/SETR P:LL\ze../SETR P:LH/g

By the way, your pattern will also happily match longer ends, eg SETR P:LLHHHHHHHH . If you need to limit the extension to two letters, use ..\\> (keyword boundary) or ..\\A\\@= (non-alphabetic lookahead).

It looks like you could just settle for:

:%s/SETR P:LL/SETR P:LH/

To exclude the preceding text from the match you can use the \\@<= look-behind assertion or \\zs :

:%s/\(SETR P:L\)\@<=L/H/
:%s/SETR P:L\zsL/H/

Similarly, for excluding the subsequent text from the match \\@= and \\ze can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM