代码之家  ›  专栏  ›  技术社区  ›  Daltron

regex:使用regex只允许简单算术

  •  0
  • Daltron  · 技术社区  · 6 年前

    所以,我有一个验证器和一个 string.replace() 为了保护我的基础 textarea 输入。

    我的验证器如下:

    Validators.pattern('-?[0-9]+([-+*/]?-?[0-9])*')
    

    基本上,我想允许所有简单的算术。

    示例:

    2*2-2
    2*2--2
    -2**2--2
    

    我不想允许多个符号超过*或+像***或+++

    验证程序应允许的示例:

    +
    +- (addition of a negative)
    -
    -- (evaluated as +)
    /
    *
    **
    

    外面的一切 integer (valid expression) integer (valid expression) integer etc. 应替换为“”。(就像在验证程序失败时增加的预防措施一样):

    +++ => +
    --- => -
    *** => **
    /// => /
    +-  => -
    */  => // (not sure what to do with this)
    

    我有类似的东西,但要成为白名单需要做些调整:

    unsafeCalculation.replace(/-?[0-9]+([-+*/]{1,2}?-?[0-9])*/, '');
    

    例子:

    2**2--2---2+++2///2 => 2**2+2-2+2/2 
    

    告诉我你认为最好的是什么 replace 正则表达式

    1 回复  |  直到 6 年前
        1
  •  1
  •   MynockSpit    6 年前

    正如注释中所提到的,您所描述的非常接近(如果不完全正确的话)解析。regex在解析方面很糟糕。要获得良好的解析教程,请查看以下内容: http://lisperator.net/pltut/parser/

    这就是说,这足够简单,你可以摆脱使用regex。您可以在同一个字符串上多次替换,而不是尝试创建一个end all-be-regex。这样读写就更清楚了。

    例如

    unsafeCalculation
      .replace(/[+]{2,}/g, '+')
      .replace(/[-]{2,}/g, '-')
      // etc,.