vim替换:#表示单个$,$ $$则无关

问题描述

我想进行以下替换:用符号#替换2 <html> <head> <script src="p5.min.js"></script> <script src="C:/full path/src/sketch.js"></script> </head> <body> <main> </main> </body 间的单词$,如果这些单词在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下使用以下命令执行此操作:

Currently,as in the case where I have 2 sets of different measures (#\tau_1,\sigma_1#) and (#\tau_2,\sigma_2#),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}$$

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

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

解决方法

您可以在vim中使用此正则表达式替换,使用负向超前和负向超前:

搜索:

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

替换:

#\1#

说明:

  • %s/:全局替换
  • \v:启动非常魔幻的模式,而不是BRE
  • \$@<!:否定性落后,断言我们之前的位置没有$
  • \$:匹配文字$
  • ([^$]+):匹配所有非$字符的1+并将其捕获在#1组中
  • \$:匹配文字$
  • \$@!:否定前瞻性断言我们前面没有$
  • #\1#:替换为由#包围的#1组的反向引用