I am trying to write a regex for split
that will result as follows:
'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', '']
Here's what I've attempted so far, it's 2 regexes and not working properly either:
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', '']
You may match and capture the parts using
/^(0*(?:[.,]0*)?)([\d.,]*?)(0*(?:[.,]0*)?)$/
See the regex demo .
Details
^
- start of string (0*(?:[.,]0*)?)
- Group 1: zero or more 0
chars followed with an optional sequence of .
or ,
and then zero or more 0
s([\\d.,]*?)
- Group 2: zero or more digits, commas or periods, but as few as possible due to the *?
lazy quantifier(0*(?:[.,]0*)?)
- Group 3: zero or more 0
chars followed with an optional sequence of .
or ,
and then zero or more 0
s$
- end of string. JS demo:
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', '']
You could take some groups and omit the whole matching string.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.