Javascript:将字符串拆分为与数组匹配的参数 [英] Javascript: Split a string into array matching parameters

查看:70
本文介绍了Javascript:将字符串拆分为与数组匹配的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string that has numbers and math operators (+,x,-, /) mixed in it

'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?

推荐答案

拆分连续的非-数字字符\D+您获得

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

如果您添加捕获组,则(\D+)您也会获得分隔符

If you add a capture group, (\D+) you get the separator too

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

如果要支持解析小数,请将正则表达式更改为/([^0-9.]+)/-注意,上面使用的\D等同于[^0-9],因此我们在这里要做的就是将.添加到字符类中

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 . 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

这篇关于Javascript:将字符串拆分为与数组匹配的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆