discrete
V2EX  ›  问与答

求一个正则表达式,为$$和$$之间的所有_前添加一个\

  •  
  •   discrete · Mar 16, 2015 · 3218 views
    This topic created in 4101 days ago, the information mentioned may be changed or developed.

    如题,下面是一个latex,为了能在ghost中配合markdown和mathjex使用,需要将_进行转义。

    $$ P_t = \frac{Nominal \ GDP}{Real \ GDP}=\frac{$Y_t}{Y_t} $$
    

    替换为:

    $$ P\_t = \frac{Nominal \ GDP}{Real \ GDP}=\frac{$Y\_t}{Y\_t} $$
    

    感激不尽。

    P.S. 我用Atom进行正则表达式替换。

    11 replies    2015-03-18 19:49:54 +08:00
    walleL
        1
    walleL  
       Mar 16, 2015
    echo '$$ P_t = \frac{Nominal \ GDP}{Real \ GDP}=\frac{$Y_t}{Y_t} $$' | sed -re '/\$\$.+\$\$/{s/_/\\_/g}'

    sed 的解法, Atom 没用过
    discrete
        2
    discrete  
    OP
       Mar 16, 2015
    @walleL 这在Mac下用不了……

    ``
    ➜ ~ cat 1 | sed -re '/\$\$.+\$\$/{s/_/\\_/g}'
    sed: illegal option -- r
    usage: sed script [-Ealn] [-i extension] [file ...]
    sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]
    ➜ ~ cat 1 | sed '/\$\$.+\$\$/{s/_/\\_/g}'
    sed: 1: "/\$\$.+\$\$/{s/_/\\_/g}": bad flag in substitute command: '}'
    ``
    P233
        3
    P233  
       Mar 16, 2015
    用 vim 吧

    :g/^\$\$.*\$\$$/s/_/\\_/g
    discrete
        4
    discrete  
    OP
       Mar 16, 2015
    @P233 好像有个inline的没适配到

    $$ \pi_t \ $

    不知为何……
    discrete
        5
    discrete  
    OP
       Mar 16, 2015
    @P233

    抱歉,是

    $$ \pi_t \ $$
    P233
        6
    P233  
       Mar 16, 2015
    @discrete 应该可以的,限制了行首和行尾必须是 $$ , 可能行尾有空格。

    或者 :g/^\$\$.*\$\$\s*$/s/_/\\_/g 行尾空格也算
    discrete
        7
    discrete  
    OP
       Mar 18, 2015
    @P233 啊还有一个问题,如果是在$$和$$之间的所有单个存在的$(也就是不会有$$以上)前添加一个\,该怎么改写呢?
    P233
        8
    P233  
       Mar 18, 2015
    vim 的正则预查我搞不定,我应该会替换全部 $ ,然后再把两个的 $$ 换回来

    :g/^\$\$.*\$\$\s*$/s/_/\\_/g
    P233
        9
    P233  
       Mar 18, 2015
    还没修改,不小心发出去了

    :g/^\$\$.*\$\$\s*$/ 匹配以 $$ 开头和结尾的行,后面跟替换命令,比如 s/\$/\\\$/g
    discrete
        10
    discrete  
    OP
       Mar 18, 2015
    @P233 我又试了几次,才发现问题所在囧:我的不一定是每行一个这样的式子,而是可能写着写着就$$ \pi_t \ $$这样……如何不匹配行而是仅匹配行内的片段?
    P233
        11
    P233  
       Mar 18, 2015
    抱歉,不了解 latex 以为是整行整行的。可以非贪婪匹配 $$ 与第一个出现的 $$,像这样 :g/\$\$.*?\$\$/ 后面跟着替换命令 s/
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4871 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 01:09 · PVG 09:09 · LAX 18:09 · JFK 21:09
    ♥ Do have faith in what you're doing.