如何用正则表达式替换字符串中的字符?

How to replace a character within a string with regex?

我有一个字符串:

let y = ".1875 X 7.00 X 8.800";

我想 return 这是一个包含 3 个数字的数组:0.1875、7.00、8.800

我需要将 .1875 转换为 0.1875,但是您不能只针对第一个字符,因为如果字符串如下所示:

let x = "7.00 X .1875 X 8.800";

or another difficult example

let y = ".50" x 1.25" x 7.125" will make one part"

这是我目前的尝试:

let numbers = x.match(/(\d*\.)?\d+/g)
numbers.map(n => parseFloat(n))


var thickness = numbers[0]
var width = numbers[1]
var length = numbers[2]


if(thickness.charAt(0) == '.'){

    let stringA = numbers[0].match(/^(\.)/g)
    let stringB = "0"

    thickness.replace(stringA, stringB)
    console.log(thickness)}

else {
     alert('failure');
}

我似乎无法替换 .在 .1875 到 0.1875 之间,非常感谢任何帮助!

这是使用正则表达式的一种方法:

let x = "7.00 X .1875 X 8.800";

const pattern = /\d*\.?\d+/g;

const numbers = [...x.matchAll(pattern)].map(Number);
console.log(numbers);


  • \d*:尽可能匹配0到无限次之间的任何数字。
  • \.?:可选匹配..
  • \d+:尽可能匹配1到无限次之间的任何数字。

从上面的评论...

The OP actually does not want "... to return this as an array of 3 numbers: 0.1875, 7.00, 8.800" but as an array of 3 stringified numbers with a sanitized/normalized number format "0.1875", "7.00", "8.800".

一种可能的方法是结合

const sampleData = `
  .1875 X 7.00 X 8.800 
  7.00 X .1875 X 8.800 
  .50" x 1.25" x 7.125" will make one part

  .1875 X 7.00 X 8.800 X 456 X 13.45.56.343.343.
`;

// see ... [(?<!\d)(?:\d*\.)?\d+]
const regXValidNumber = /(?<!\d)(?:\d*\.)?\d+/g;

console.log(
  sampleData
    // retrieving the array of
    // valid stringified numbers.
    .match(regXValidNumber)
);
console.log(
  sampleData
    // retrieving the array of
    // valid stringified numbers.
    .match(regXValidNumber)
    // normalizing the number format.
    .map(str => str.replace(/^\./, '0$&'))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }