Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Match all decimals but the first one

What would the regex pattern be to match all decimals but the first one? I'm using javascript's replace(), and would like to remove all but the first decimal in a string.

Examples:

1.2.3.4.5 --> 1.2345

.2.3.4.5 --> .2345

1234.. --> 1234.
like image 698
hookedonwinter Avatar asked Nov 18 '10 22:11

hookedonwinter


People also ask

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What is Regex101?

Regex101.com is an interactive regular expression console that lets you debug your expressions in real-time.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"


1 Answers

You could do something like this:

function parseAndNormalizeDecimal(dec) {
  var i = 0;
  var result = dec.replace(/\./g, function(all, match) { return i++===0 ? '.' : ''; });
  return result;
}
like image 66
James Kovacs Avatar answered Sep 28 '22 08:09

James Kovacs