Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a zero followed by 6 decimal places

I'm trying to use Regex to match a zero followed by a dot and exactly 6 digits. Such as --> 0.274538

The 6 digits can be any number 0-9. Also, any characters (including blank spaces) may exist before or after the match.

I would like to trim the tailing 4 digits off of the match, so that the result is a zero followed by 2 decimal places (ie 0.27).

I'm using this regex inside a Javascript string replace function. I'm including the "g" modifier, as there will be several matches within the string.

I'm not very good with regex, but I think the following code is pretty close to what I need...

var replaced = string.replace(/[0]\.[0-9]{6}$/g, X);

Only thing is... I'm not sure what to use for the 'replace' value here (X). If there was only one match expected, then I could just use "slice" on the replaced string. But since I am expecting several regex matches in the string, what should I use for the "X" value? Or is there a better way to go about this?

like image 370
JustAnotherCoder Avatar asked Mar 15 '23 09:03

JustAnotherCoder


2 Answers

You can use capturing group:

var s = '0.274538'
var r = s.replace(/\b(0\.\d{2})\d{4}\b/g, '$1');
//=> 0.27
  • \b is for word boundary.
  • (..) is captured group #1 to grab 0 followed by a DOT and 2 decimal point.
  • $1 is back-reference of captured group#1
like image 69
anubhava Avatar answered Mar 27 '23 00:03

anubhava


This is another way of doing it, with a function as a the replace parameter:

var regex = /0\.\d{6}/g;
var num = '0.543456';

var trimmed = num.replace(regex, function(match){
  return match.substr(0, match.length - 4);
  });

console.log(trimmed);
like image 41
MinusFour Avatar answered Mar 27 '23 00:03

MinusFour