简体   繁体   English

将字符串拆分为浮点数和字符数组

[英]Splitting a string into an array of floats and characters

We are working with a string that can contain integers, floats and characters. 我们正在使用可以包含整数,浮点数和字符的字符串。

Example: 例:

.12A1.3B.5CD .12A1.3B.5CD

I want to take that string and turn it into an array of numbers and characters that looks like 我想把那个字符串变成一个数字和字符数组,看起来像

[.12,A,1.3,B,.5,C,0,D] [.12,A,1.3,B,.5,C,0,D]

(when there is no number in front of the letter, it is assumed to be a 0) (当字母前没有数字时,假定为0)

I have tried different regex combinations and can't get any to work like: 我尝试了不同的正则表达式组合,却无法正常工作:

str.match(/[a-zA-Z]+?[0-9]*\.?[0-9]+/g)

but it gives me the result of: 但这给了我以下结果:

["12", "A", "1", "3", "B", "5", "CD"] [“ 12”,“ A”,“ 1”,“ 3”,“ B”,“ 5”,“ CD”]

chopping off the decimal point and not separating the "D" to "0,D" 切掉小数点并且不将“ D”分隔为“ 0,D”

Again the desired result is [.12,A,1.3,B,.5,C,0,D]. 同样,期望的结果是[.12,A,1.3,B,.5,C,0,D]。

Any guesses? 有什么猜想吗?

You could replace the missing zeros and match the parts. 您可以替换丢失的零并匹配零件。 Later map the value after checking for number or string. 稍后在检查数字或字符串之后映射值。

 var string ='.12A1.3B.5CD', array = string .replace(/((^|[az])(?=\\.))|([az](?=[az]))/gi, '$&0') .match(/[.0-9]+|[az]/gi) .map(v => v == +v ? +v : v); console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can add a zero after each letter if it is followed by another letter and then split on letters: 您可以在每个字母之后添加零(如果后面紧跟另一个字母,然后按字母分割):

 var s = ".12A1.3B.5CD"; console.log( s.replace(/([az])(?=[az])/gi, "$1"+"0").split(/([az])/i).filter(x => x != "") ) 

With String.match() , Array.reduce() and isNaN() functions: 使用String.match()Array.reduce()isNaN()函数:

 var s = '.12A1.3B.5CD', prev, result = s.match(/(\\d*\\.)?\\d+|[a-zA-Z]/g).reduce(function(a, v){ v = +v || v; if (a.length > 1 && +v !== v && isNaN(prev)) a.push(0); a.push(v); prev = v; return a; }, []); console.log(result) 

"Speed" comparison: “速度”比较:

在此处输入图片说明

This should do the trick: 这应该可以解决问题:

str.match(\\([a-zA-Z]|[0-9]*\\.?[0-9]+)\\g)

then using javascript you should insert a 0 into the array between consecutive letters. 然后使用javascript,您应该在连续字母之间的数组中插入0。

A good website to check out regex's: https://regex101.com/r/vhnv2M/1 一个查看正则表达式的好网站: https : //regex101.com/r/vhnv2M/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM