【发布时间】:2020-12-07 06:56:25
【问题描述】:
我目前正在尝试向我的 discord 机器人添加简单的数学求解功能,这是通过首先消除用户输入(以解决安全问题),然后通过 new Function 运行它来完成的。问题是我希望 Math 对象中当前的所有函数对用户来说都是独立的,这就是我的意思:
要获得数字的平方根,在 JS 内部我可以使用 Math.sqrt(25)。我不希望用户必须处理Math.,所以理想情况下他们只会使用sqrt(25)。总消息可能类似于:!solve sqrt(25),它将返回 5。
因为消息内容已经是一个字符串,并且已经被消毒,所以这个字符串中唯一的东西将是:数字、运算(+、-、*、/、^ 或 **)或数学函数(cos、 sin、sqrt 等)。因为这些数学函数是这里唯一的“单词”,解决这个问题的一个非常简单的方法是只取这个字符串中的所有“单词”,在每个单词之前添加Math.,然后求解方程。
这是伪代码和示例:
Psudocode: | Example:
1. Get user input | input = '! solve 5 + cos(10) / sqrt(50)*random()'
2. Trim input to only the equation | input = '5 + cos(10) / sqrt(50)*random()'
3. Add Math. to beginning of words | input = '5 + Math.cos(10) / Math.sqrt(50)*Math.random()'
4. Compile into result variable | result = new Function(`return ${input}`);
5. If step 4 failed, tell user | send(`bla is not a math function`); //<-- if input was bla(50)
6. Send user result | send(result);
除了第 4 步之外,我已经完成了所有步骤,这就是我需要了解的地方。我发现了这个 PHP- Adding ":" character to all words in string PHP 函数,我的大脑似乎无法理解,还有这个 Regular Expression - Add a character before/after each word 记事本答案,除了替换器本身是一个正则表达式,Js 的 string.replace() 不接受,这将起作用打字稿。有人能指出我正确的方向吗?
【问题讨论】:
标签: javascript regex