使用java脚本或正则表达式从值中分割数字和字符串

Split number and string from the value using java script or regex

本文关键字:分割 数字 字符串 java 脚本 正则表达式 使用      更新时间:2023-09-26

我有一个值"4.66lb"

和我想分开"4.66"answers"lb"使用正则表达式。

我尝试了下面的代码,但它只分隔数字"4,66"!!但是我想要的值是4.66和lb。

var text = "4.66lb";
var regex = /('d+)/g;
alert(text.match(/('d+)/g));

试一试:

var res = text.match(/('d+(?:'.'d+)?)('D+)/);

res[1]包含4.66
res[2]lb

为了匹配4/5lb,你可以使用:

var res = text.match(/('d+(?:[.'/]'d+)?)('D+)/);

你也可以使用字符类,

> var res = text.match(/([0-9'.]+)('w+)/);
undefined
> res[1]
'4.66'
> res[2]
'lb'

让我用一个例子来解释

var str = ' 1 ab 2 bc 4 dd';   //sample string
str.split(/'s+'d+'s+/)
result_1 = ["", "ab", "bc", "dd"]  //regex not enclosed in parenthesis () will split string on the basis of match expression
str.split(/('s+'d+'s+)/)        //regex enclosed in parenthesis () along with above results, it also finds all matching strings
result_2 = ["", " 1 ", "ab", " 2 ", "bc", " 4 ", "dd"] 
//here we received two type of results: result_1 (split of string based on regex) and those matching the regex itself
//Yours case is the second one
//enclose the desired regex in parenthesis
solution : str.split(/('d+'.*'d+[^'D])/)