vim 替换 : # 对于单个 $ 并且如果 $$ 则无事可做

vim substitution : # for a single $ and nothing to do if $$

我想做以下替换:将位于 2 $ 之间的单词 $ 替换为符号 #,如果这些单词位于 2 $$ 之间,则不执行任何操作。

例如,在本文中:

Currently, we are able to make cross correlations (understand "combine" to have better constraints on cosmological parameters) between weak lensing (WL) and photometric Galaxy clustering (GCph). When I say combine, as in the case where I have 2 sets of different measures ($\tau_1, \sigma_1$) and ($\tau_2, \sigma_2$), well, if I consider the Gaussian errors, it is shown quite easily (by Maximum Likelihood Estimation) that the estimator $\sigma_{\hat {\tau}}$ the most representative matches the relation:
    
    
$$\dfrac{1}{\sigma_{\hat{\tau}}^{2}}=\dfrac{1}{\sigma_1^2}+\dfrac{1}{\sigma_2^2}$$

替换会得到:

Currently, we are able to make cross correlations (understand "combine" to have better constraints on cosmological parameters) between weak lensing (WL) and photometric Galaxy clustering (GCph). When I say combine, as in the case where I have 2 sets of different measures (#\tau_1, \sigma_1#) and (#\tau_2, \sigma_2#), well, if I consider the Gaussian errors, it is shown quite easily (by Maximum Likelihood Estimation) that the estimator #\sigma_{\hat {\tau}}# the most representative matches the relation:


$$\dfrac{1}{\sigma_{\hat{\tau}}^{2}}=\dfrac{1}{\sigma_1^2}+\dfrac{1}{\sigma_2^2}$$

我尝试在 vim 下使用以下命令执行此操作:

%s/$[^$]\(.*\)$[^$]/##/g

%s/$[^$]\(.\{-}\)$[^$]/##/g

但这不起作用。我看不到我的错误。

您可以在 vim 中使用负前瞻和负后瞻来使用此正则表达式替换:

搜索:

:%s/\v$@<!$([^$]+)$$@!/##/g

替换:

##

解释:

  • %s/:全局替换
  • \v: 开始非常神奇的模式而不是 BRE
  • $@<!:否定回顾断言我们在之前的位置
  • 没有$
  • $:匹配文字$
  • ([^$]+):匹配任何非 $ 的字符的 1+ 并在组 #1
  • 中捕获它
  • $:匹配文字$
  • $@!:否定前瞻断言我们没有$提前
  • ##:用 #
  • 包围的第 1 组的 back-reference 替换