search - 替换某些字符,但不替换匹配项中找到的字符

标签 search vim pattern-matching

昨天,我尝试替换文本中的所有 ( ),但不替换在先前搜索的匹配项中找到的内容。我找不到好的解决方案。我是一一改的。

这是我的原文:

(Peter Jackson) is the man who..... (John Johnson) is the man who....  
and (John Johnson) is also the man who.. not as (Jon Johnson)
more (letters) etc.

我的搜索模式:/(\a*\sJohnson)
如何将文本中的所有 ( ) 字符替换为 [ ],而不是匹配中找到的字符?

结果应该是:

[Peter Jackson] is the man who..... (John Johnson) is the man who....  
and (John Johnson) is also the man who.. not as (Jon Johnson)
more [letters] etc.

编辑
是否有一种简单的方法可以替换文本中的一个或多个任意字符,但不能替换匹配中的这些字符?

最佳答案

您可以使用\@!( Negative Lookahead ):

:%s/(\%(\a*\sJohnson\)\@!\([^)]*\))/[\1]/g
     ->|............|<---
  • \%(...\)\@!负向预测
  • \([^)]*\) 将匹配除 ) 之外的所有内容。
  • 我使用 \%( 来忽略捕获的组,否则您需要 /[\2]/

关于search - 替换某些字符,但不替换匹配项中找到的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10061055/

相关文章:

C++ 查找所有 .wav 文件

java - 用于搜索的同义词数据结构

vim - Vim 可以放大和缩小吗?

vi 丢失的 Git 提交消息

javascript - 一个字符串或模式的正则表达式

Scala Map 模式匹配

javascript - 如何通过添加 for 循环来遍历 data.games 来重写搜索函数,并在搜索时添加它显示的分数?

Codeigniter:如何对搜索结果进行分页

php - 用于 PHP 的 VIM : List if( )'s and include()' s in Taglist

types - Rust 中匹配参数化类型