Javascript:将字符串拆分为匹配参数的数组

2023-12-09

我有一个包含数字和数学运算符的字符串(+,x,-, /) 混入其中

'12+345x6/789'

我需要将其转换为由这些数学运算符分隔的数组。

[12, +, 345, x, 6, /, 789]

执行此操作的简单方法是什么?


连续分割非数字 chars \D+ you get

console.log ('12+345x6/789'.split (/\D+/))
// [ '12', '345', '6', '789' ]

如果您添加一个捕获组, (\D+)你也得到了分隔符

console.log ('12+345x6/789'.split (/(\D+)/))
// [ "12", "+", "345", "x", "6", "/", "789" ]

如果您想支持解析小数,请将正则表达式更改为/([^0-9.]+)/- 笔记,\D上面使用的等价于[^0-9],所以我们在这里所做的就是添加.到字符类

console.log ('12+3.4x5'.split (/([^0-9.]+)/))
// [ "12", "+", "3.4", "x", "5" ]

以及编写程序其余部分的可能方法

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript:将字符串拆分为匹配参数的数组 的相关文章

随机推荐