【问题标题】:How to insert thousand separators only before the decimal separator如何仅在小数分隔符之前插入千位分隔符
【发布时间】:2012-05-05 10:40:41
【问题描述】:

我使用这个正则表达式将千位分隔符放在一个字符串中:

while matchstr(mystr, '\(\d\)\(\d\{3}\)\(\D\|\s\|$\)') != ''
    let mystr = substitute(mystr, '\(\d\)\(\d\{3}\)\(\D\|\s\|$\)', '\1.\2\3', 'g')
endwhile

对于

let mystr = '2000000'

上面的代码给出了

2.000.000

问题是当有小数分隔符时,它也会在小数分隔符后面的数字的小数部分放置千位分隔符(以下是逗号)。

例如,

let mystr = '2000000,2346'

导致

2.000.000,2.346

当我想要它的时候

2.000.000,2346

我尝试修改上面的代码,但没有找到令人满意的解决方案。 谁能帮帮我?

【问题讨论】:

    标签: regex string vim replace


    【解决方案1】:

    使用以下对substitute() 函数的调用而不是整个函数 问题中列出的循环。

    substitute(s, '\(\d,\d*\)\@<!\d\ze\(\d\{3}\)\+\d\@!', '&.', 'g')
    

    【讨论】:

    • 非常感谢!效果很好!我想了解你做了什么,但这并不容易。
    【解决方案2】:

    试试这个(仅适用于正整数):

    查找

    (?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))
    

    替换为

    ,
    

    我还没有尝试过vim 是否可行。但该模式与 PCRE 兼容。


    说明

    <!--
    (?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))
    
    Options: case insensitive; ^ and $ match at line breaks
    
    Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=[0-9])»
       Match a single character in the range between “0” and “9” «[0-9]»
    Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=(?:[0-9]{3})+(?![0-9]))»
       Match the regular expression below «(?:[0-9]{3})+»
          Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
          Match a single character in the range between “0” and “9” «[0-9]{3}»
             Exactly 3 times «{3}»
       Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?![0-9])»
          Match a single character in the range between “0” and “9” «[0-9]»
    -->
    

    【讨论】:

    • Tnx Cylian,我找不到 vim 变体。 prce 正则表达式与 vim 正则表达式非常不同
    • 我个人之前从未使用过vim,但是它的帮助文件usr_27.txt&gt;&gt;section 27.4 描述了{ 必须被转义,例如\{。所以,你可以试试:(?&lt;=[0-9])(?=(?:[0-9]\{3})+(?![0-9]))...
    • ?&lt;= --> \@&lt;=,我将所有内容都更改为 vim 正则表达式,但它不起作用。 vim 中的零宽度断言是不同的。我想他们也必须在哪里。体育在\@&lt;= 中更改?&lt;= 会出现错误:\@&lt;=