如何用正则表达式替换字符串中的字符?
我有一个字符串:
let y = ".1875 X 7.00 X 8.800";
我想将其作为 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 中,非常感谢任何帮助!
I have a string:
let y = ".1875 X 7.00 X 8.800";
I would like to return this as an array of 3 numbers: 0.1875, 7.00, 8.800
I need to convert .1875 into 0.1875, however you can't just target the first character because what if the string is like so:
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"
This is my attempt so far:
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');
}
I can't seem to replace the . in .1875 to 0.1875, any help much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从上面的评论...
一种可能的方法是结合
/(?
... 和 ...
.replace(/^\./, '0$&' )
...有效数字格式。From the above comment ...
A possible approach was the combination of
/(?<!\d)(?:\d*\.)?\d+/g
... and ....replace(/^\./, '0$&')
... valid number formats.这是使用正则表达式执行此操作的一种方法:
\d*
:尽可能匹配 0 次到无限次之间的任何数字。\.?
:可选地匹配.
。\d+
:尽可能匹配 1 次到无限次之间的任意数字。Here is one way to do so using regex:
\d*
: Matches any digit between 0 and unlimited times, as much as possible.\.?
: Optionally matches.
.\d+
: Matches any digit between 1 and unlimited times, as much as possible.