正面前瞻千位分隔符的正则表达式,在点之后不会是马赫数 [英] Regex for positive lookahead thousand separator that would not mach numbers after dot

查看:76
本文介绍了正面前瞻千位分隔符的正则表达式,在点之后不会是马赫数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下正则表达式在javascript中将逗号插入数字。

I am using following regex to 'insert' commas into numbers in javascript.

(\d)(?=(\d{3})+(?!\d))

效果很好但是当使用十进制数时,它会失败,例如10000.001223456(结果是1,234,568.0,000,454,554)

It works very well with integers however when working with decimal numbers it fails cases like 10000.001223456 (result is 1,234,568.0,000,454,554)

在'。'找到匹配后,正则表达式会发生什么变化并将其替换为,

What happens regex looks ahead after '.' finds match and replaces it with ,

此处示例

我尝试通过添加负面观察来解决问题好运,

I tried remedy it by adding negative lookbehind without luck,

((\d)(?=(\d{3})+(?!\d))(?<!\.))

因为'。'可以在任何位置按顺序,我不能使用 * ,也不能 +

since '.' can be at any position in sequence and I cannot use * nor +.

如何制作一些特定符号后不匹配的正则表达式(在'。'之后的特定情况下)?

推荐答案

您只能通过3个步骤实现此目的:

You can achieve this only in 3 steps:


  1. 将数字拆分为整数和小数部分

  2. 修改整数部分

  3. 加入。

JS中没有可变宽度的后视,这里非常方便。

There is no variable-width look-behind in JS that would be very handy here.

var s = ".12345680000454554";
//Beforehand, perhaps, it is a good idea to check if the number has a decimal part
if (s.indexOf(".") > -1) { 
    var splts = s.split(".");
    //alert(splts);
    splts[0] = splts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
    //alert(splts[0]);
    s = splts.join(".");
    alert(s);
  }
else
  {
     alert(s.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
  }

这篇关于正面前瞻千位分隔符的正则表达式,在点之后不会是马赫数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆