[英]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.