我正在尝试编写类似 eval() 的东西,以下是一些要求:
if the expression contains non-numeric character other than [+, -, *, /, .],
or [+, -] is followed by [*, /],
or [+, -, *, /] is not proceeded by a numeric e.g."10-",
or [*, /] is not preceded by a numeric e.g."-10" is valid, "*10" is not valid
throw an exception
我有以下代码:
if (expression.match(/[^+\-*/\d.]/) ||
expression.match(/[+-](?=[*/])/) ||
expression.match(/[+\-*/]($|[^+\-.\d])/) ||
expression.match(/(^|[^+\-.\d])[*/]/))
throw errors.ExpressionParserError;
当表达式按照上面的方式分开时,它工作得很好,但是当我将它们与 |(OR) 组合时,它不再抛出异常
if (expression.match(/[^+\-*/\d.] | [+-](?=[*/]) | [+\-*/]($|[^+\-.\d]) | (^|[^+\-.\d])[*/]/))
throw errors.ExpressionParserError;
例如“d * 1”应该落在表达式的第一部分 [^+-*/\d.]
我在这里错过了什么?谢谢。
最佳答案
有两件事:
|
周围有空格。这些空间很重要。- 您可能需要对各个部分进行分组,以确保正确应用交替(可能对于非捕获组:
(?:...)
)。
例如:
if (expression.match(/(?:[^+\-*/\d.])|(?:[+-](?=[*/]))|(?:[+\-*/]($|[^+\-.\d]))|(?:(^|[^+\-.\d])[*/])/))
// -------------------^^^-----------^^^--------------^^^----------------------^^^-------------------^
throw errors.ExpressionParserError;
旁注:要测试匹配,请使用 rex.test(str)
而不是 str.match(rex)
。如果您的唯一目标是测试匹配,则无需构建结果数组。
关于javascript - 正则表达式单独工作,但与 | 结合使用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798690/