我想使用vim的替换函数(:%s)来搜索和替换某种代码模式.例如,如果我有类似于以下代码:
if(!foo)
我想用以下代替:
if(foo == NULL)
然而,foo只是一个例子.变量名可以是任何名称.
这是我为我的vim命令提出的:
:%s/if(!.*)/if(.* == NULL)/gc
它正确搜索语句,但它试图用".*"而不是那里的变量(即"foo")替换它.有没有办法用vim做我要问的事情?
如果没有,是否还有其他编辑器/工具可以帮我修改这些?
提前致谢!
您需要使用捕获分组和反向引用才能实现:
Pattern String sub. flags |---------| |------------| |-|
:%s/if(!\(.*\))/if(\1 == NULL)/gc
|---| |--|
| ^
|________|
The matched string in pattern will be exactly repeated in string substitution
:help /\(
\(\) A pattern enclosed by escaped parentheses. /\(/\(\) /\) E.g., "\(^a\)" matches 'a' at the start of a line. E51 E54 E55 E872 E873 \1 Matches the same string that was matched by /\1 E65 the first sub-expression in \( and \). {not in Vi} Example: "\([a-z]\).\1" matches "ata", "ehe", "tot", etc. \2 Like "\1", but uses second sub-expression, /\2 ... /\3 \9 Like "\1", but uses ninth sub-expression. /\9 Note: The numbering of groups is done based on which "\(" comes first in the pattern (going left to right), NOT based on what is matched first.