nanobar
nanobar

Reputation: 66355

Split number by leading and trailing zeros

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', '']

Upvotes: 2

Views: 406

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

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; }

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

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 0s
  • ([\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 0s
  • $ - 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', '']

Upvotes: 2

Related Questions