替换同时保留某些“词"在 vi/vim 中 [英] Replace while keeping certain "words" in vi/vim
问题描述
例如,如果我有 $asd['word_123']
并且我想用 $this->line('word_123')
替换它,保持'word_123'.我怎么能这样做?
For example, if I have $asd['word_123']
and I wanted to replace it with $this->line('word_123')
, keeping the 'word_123'. How could I do that?
通过使用:
%s/asd\[\'.*\'\]/this->line('.*')/g
我将无法保持两者之间的措辞.请赐教.
I will not be able to keep the wording in between. Please enlighten me.
推荐答案
使用正则表达式,你可以像 :%s/\$asd\['\([^']*\)'\]/$this->line('\1')/g
Using regex, you could do something like :%s/\$asd\['\([^']*\)'\]/$this->line('\1')/g
%s
- 替换整个文件
\$asd\['
- 匹配$asd['".注意 $
和 [
需要转义,因为它们在正则表达式中具有特殊含义.
\$asd\['
- match "$asd['". Notice the $
and [
need to be escaped since these have special meaning in regex.
\([^']*\)
- \( \)
可用于选择所谓的原子",以便您可以在更换.[^']
表示任何非 '
,*
表示匹配 0 个或多个.
\([^']*\)
- the \( \)
can be used to select what's called an "atom" so that you can use it in the replacement. The [^']
means anything that is not a '
, and *
means match 0 or more of them.
'\]
- 结束我们的比赛.
'\]
- finishes our match.
$this->line('\1')
- 替换为我们想要的,\1
替换为我们之前匹配的原子.
$this->line('\1')
- replaces with what we want, and \1
replaces with our matched atom from before.
g
- 对每行的多个匹配执行此操作.
g
- do this for multiple matches on each line.
您也可以使用宏来代替正则表达式.例如,
Instead of regex you could also use a macro. For example,
qq/\$asd<Enter>ct'$this->line(<Esc>f]r)q
然后 @q
根据需要多次.您也可以在@q
使用一次后@@
,或者如果您想使用它80次,您可以80@q
.
then @q
as many times as you need. You can also @@
after you've used @q
once, or you can 80@q
if you want to use it 80 times.
在某些情况下,使用 :norm
可能是最好的选择.例如,如果您有一小段代码并且您正在匹配一个唯一的字符或位置.如果您知道$"只出现在特定代码块的$asd"中,您可以直观地选择它并
In some cases, using :norm
may be the best option. For example, if you have a short block of code and you're matching a unique character or position. If you know that "$" only appears in "$asd" for a particular block of code you could visually select it and
:norm $T$ct'this->line(<C-v><Esc>f]r)<Enter>
关于更有效地使用 :norm 的讨论,请阅读 :help :norm
和 这个 reddit 帖子.
For a discourse on using :norm more effectively, read :help :norm
and this reddit post.
这篇关于替换同时保留某些“词"在 vi/vim 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!