【问题标题】:Add characters in front of all words Regex/Typescript [duplicate]在所有单词Regex / Typescript前面添加字符[重复]
【发布时间】: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


    【解决方案1】:

    一旦字符串被清理,就不需要替换任何东西,如果你从Math中提取你想要允许的方法或属性:

    const input = '5 + cos(10) / sqrt(50)*random()';
    const { sqrt, pow, random, cos, sin, PI } = Math;
    console.log(eval(input));

    【讨论】:

      【解决方案2】:

      @blex 的回答很好。这是对字母字符进行全局搜索和替换的另一种解决方案:

      function evalExpr(str) {
        try {
          str = str.replace(/\b([a-z]+ *\()/g, 'Math.$1');
          return eval(str);
        } catch(e) {
          return 'Error evaluating "' + str + '"';
        }
      }
      
      const input = 'round((5 + cos(10) / sqrt(50)) * 10) / 10';
      console.log(input + ' = ' + evalExpr(input));

      正则表达式有一个单词边界,后跟 1+ alpha 字符,后跟可选空格,后跟左括号

      【讨论】:

        猜你喜欢
        • 2020-04-12
        • 2020-03-29
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 2012-10-18
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多