[英]Javascript: Split a string into array matching parameters
I have a string that has numbers and math operators ( +
, x
, -
, /
) mixed in it 我有一个包含数字和数学运算符(
+
, x
, -
, /
)的字符串
'12+345x6/789'
I need to convert it into an array seperated by those math operators. 我需要将其转换为由这些数学运算符分隔的数组。
[12, +, 345, x, 6, /, 789]
What is a simple way of doing this? 这样做的简单方法是什么?
Splitting on consecutive non-digit chars \\D+
you get 在连续的非数字字符
\\D+
上进行拆分
console.log ('12+345x6/789'.split (/\\D+/)) // [ '12', '345', '6', '789' ]
If you add a capture group , (\\D+)
you get the separator too 如果添加捕获组 ,
(\\D+)
,也会获得分隔符
console.log ('12+345x6/789'.split (/(\\D+)/)) // [ "12", "+", "345", "x", "6", "/", "789" ]
If you want to support parsing decimals, change the regexp to /([^0-9.]+)/
- Note, \\D
used above is equivalent to [^0-9]
, so all we're doing here is adding .
如果要支持解析小数,请将regexp更改为
/([^0-9.]+)/
注意,上面使用的\\D
等效于[^0-9]
,因此我们在这里所做的只是添加.
to the character class 到角色类
console.log ('12+3.4x5'.split (/([^0-9.]+)/)) // [ "12", "+", "3.4", "x", "5" ]
And a possible way to write the rest of your program 还有一种编写其余程序的可能方法
const cont = x => k => k (x) const infix = f => x => cont (f (x)) const apply = x => f => cont (f (x)) const identity = x => x const empty = Symbol () const evaluate = ([ token = empty, ...rest], then = cont (identity)) => { if (token === empty) { return then } else { switch (token) { case "+": return evaluate (rest, then (infix (x => y => x + y))) case "x": return evaluate (rest, then (infix (x => y => x * y))) case "/": return evaluate (rest, then (infix (x => y => x / y >> 0))) default: return evaluate (rest, then (apply (Number (token)))) } } } const parse = program => program.split (/(\\D+)/) const exec = program => evaluate (parse (program)) (console.log) exec ('') // 0 exec ('1') // 1 exec ('1+2') // 3 exec ('1+2+3') // 6 exec ('1+2+3x4') // 24 exec ('1+2+3x4/2') // 12 exec ('12+345x6/789') // 2
If you are unconcerned with whitespace, all you need is 如果您不关心空格,那么您所需要做的就是
'12+345x6/78-9'.match(/\d+|[\+-\/x]/g);
which splits the string into numbers and the +
, -
, \\
, and x
tokens. 它将字符串分成数字和
+
, -
, \\
和x
标记。
'use strict'; const tokens = '12+345x6/78-9'.match(/\\d+|[\\+-\\/x]/g); console.log(tokens);
To handle whitespace, consider 要处理空格,请考虑
'12+3 45 x6/78-9'.match(/\d|\d[\s\d]\d|[\+-\/x]/g);
which splits the string into numbers (optionally allowing whitespace as a digit separator within a single number) and +
, -
, \\
, and x
. 它将字符串拆分为数字(可选地允许在单个数字内使用空格作为数字分隔符)和
+
, -
, \\
和x
。
'use strict'; const tokens = '12+3 45 x6/78-9'.match(/\\d+\\s?\\d+|\\d+|[\\+-\\/x]/g); console.log(tokens);
这将工作
console.log('12+345x6/789'.match(/\\D+|\\d+/g))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.