如何仅在小数分隔符之前插入千位分隔符

时间:2012-05-05 10:40:42

标签: regex string vim replace

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

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

我尝试调整上述代码,但没有找到令人满意的解决方案。 任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

尝试此操作(仅适用于正整数):

使用

查找
(?<=[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]»
-->