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

you*_*t13 1 regex vim replace pattern-matching

我想做以下替换:用符号 #替换$位于 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}$$
Run Code Online (Sandbox Code Playgroud)

替换将给出:

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}$$
Run Code Online (Sandbox Code Playgroud)

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

%s/\$[^\$]\(.*\)\$[^\$]/#\1#/g
Run Code Online (Sandbox Code Playgroud)

或者

%s/\$[^\$]\(.\{-}\)\$[^\$]/#\1#/g
Run Code Online (Sandbox Code Playgroud)

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

anu*_*ava 6

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

搜索:

:%s/\v\$@<!\$([^$]+)\$\$@!/#\1#/g
Run Code Online (Sandbox Code Playgroud)

替代品:

#\1#
Run Code Online (Sandbox Code Playgroud)

解释:

  • %s/: 全球替代
  • \v: 启动非常神奇的模式而不是 BRE
  • \$@<!:否定后视断言我们$在之前的位置没有
  • \$: 匹配文字 $
  • ([^$]+): 匹配任何不是的字符的 1+$并将其捕获在组 #1 中
  • \$: 匹配文字 $
  • \$@!:否定前瞻断言我们没有$前进
  • #\1#: 替换为组 #1 的反向引用 #

  • 谢谢,效果很好!我不熟悉`([^$]+)`捕获到组`#1`,我通常使用`\(.\{-}\)`或`\(.*\)`,我必须深入研究这部分。问候 (2认同)