繁体   English   中英

通过前导零和尾随零分割数字

[英]Split number by leading and trailing zeros

我正在尝试为split编写一个正则表达式,结果如下:

'4.82359634' -> ['', '4.82359634', '']
'0.82300634' -> ['0.', '82300634', '']
'5.10000000' -> ['', '5.1', '0000000']
'5,10000000' -> ['', '5,1', '0000000'] // Handle commas or dots in middle section
'0.00000274' -> ['0.00000', '274', '']

这是我到目前为止所尝试的,它是 2 个正则表达式,并且也无法正常工作:

 function splitZeros(v) { const [leftAndMiddle, right] = v.split(/(0+$)/).filter(Boolean); const [left, middle] = leftAndMiddle.split(/(^[0,.]+)/).filter(Boolean) console.log({ left, middle, right }) } // (NOT working properly), comments are desired results. splitZeros("4.82359634"); // ['', '4.82359634', ''] splitZeros("0.82359634"); // ['0.', '82359634', ''] splitZeros("5.10000000"); // ['', '5.1', '0000000'] splitZeros("5,10000000"); // ['', '5,1', '0000000'] splitZeros("0.00000274"); // ['0.00000', '274', '']

您可以使用匹配和捕获部件

/^(0*(?:[.,]0*)?)([\d.,]*?)(0*(?:[.,]0*)?)$/

请参阅正则表达式演示

细节

  • ^ - 字符串的开始
  • (0*(?:[.,]0*)?) - 第 1 组:零个或多个0字符后跟可选的. ,然后零个或多个0 s
  • ([\\d.,]*?) - 第 2 组:零个或多个数字、逗号或句点,但由于*? 惰性量词
  • (0*(?:[.,]0*)?) - 第 3 组:零个或多个0字符后跟可选的. ,然后零个或多个0 s
  • $ - 字符串的结尾。

JS演示:

 function splitZeros(v) { const [_, left, middle, right] = v.match(/^(0*(?:[.,]0*)?)([\\d.,]*?)(0*(?:[.,]0*)?)$/); console.log({ left, middle, right }) } splitZeros("4.82359634"); // ['', '4.82359634', ''] splitZeros("0.82359634"); // ['0.', '82359634', ''] splitZeros("5.10000000"); // ['', '5.1', '0000000'] splitZeros("5,10000000"); // ['', '5,1', '0000000'] splitZeros("0.00000274"); // ['0.00000', '274', '']

您可以采用一些组并省略整个匹配字符串。

 const split = s => s.match(/^([0.,]*)(.*?)(0*)$/).slice(1); var data = [ '4.82359634', // ['', '4.82359634', ''] '0.82359634', // ['0.', '82359634', ''] '5.10000000', // ['', '5.1', '0000000'] '5,10000000', // ['', '5,1', '0000000'] // Handle commas or dots in middle section '0.00000274', // ['0.00000', '274', ''] ]; console.log(data.map(split));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM