英文:
String 'Regex' Validation for below scenario
问题
// 我想验证表达式字符串是否符合以下情况
// 1. 表达式应使用 variables 数组的值
// 2. 表达式不应包含除允许的数学函数之外的内容。
// 我尝试了下面的代码
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan'];
var expression= 'Sin(B)+Tan(B)+100+acos(A)';
// 对于变量检查,我尝试了这个
let expressionVariables = expression.replace(/Sin|Log|Exp|Tan|Pos|Rnd|[^A-Za-z]/ig,"");
let expressionUnUsedVar= variables.filter(v=> !expressionVariables.includes(v));
英文:
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)+C'
I want to validate expression string match below scenario
- expression should use variables array values
- expression should not contain other then allowed math functions.
I tried below code
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)'
for variable check I tried this
let expressionVariables = value.replace(/Sin|Log|Exp|Tan|Pos|Rnd|[^A-Za-z]/ig,"");
let expressionUnUsedVar= variables.filter(v=> !expressionVariables.includes(v));
I don't know how to write for both scenario for regex it's not a problem for two different regex.
答案1
得分: 1
你可以使用正则表达式提取所有变量和函数名称,然后检查它们是否包含在允许的函数和变量列表中(区分大小写):
function testExpression(expression, vars, funcs) {
const usedVariables = expression.match(/\b[a-z]+\b(?!\s*\()/gi) || [];
const usedFunctions = expression.match(/\b[a-z]+\b(?=\s*\()/gi) || [];
return usedVariables.every(v => vars.includes(v)) && usedFunctions.every(func => funcs.includes(func));
}
var variables = ['A', 'B'];
var allowedMathFunc = ['Sin', 'Cos', 'Tan'];
var expression = 'Sin(B)+Tan(B)+100+acos(A)+C';
console.log(testExpression(expression, variables, allowedMathFunc));
console.log(testExpression('Sin(B)+Tan(B)+100+Cos(A)+C', ['A', 'B', 'C'], ['Sin', 'Cos', 'Tan']));
希望这有所帮助。
英文:
You can use regex to extract all variables and function names, and then check them if they're included in the allowed function and variable lists (case sensitive):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function testExpression(expression, vars, funcs) {
const usedVariables = expression.match(/\b[a-z]+\b(?!\s*\()/gi) || [];
const usedFunctions = expression.match(/\b[a-z]+\b(?=\s*\()/gi) || [];
return usedVariables.every(v => vars.includes(v)) && usedFunctions.every(func => funcs.includes(func));
}
var variables = ['A','B'];
var allowedMathFunc = ['Sin','Cos','Tan']
var expression= 'Sin(B)+Tan(B)+100+acos(A)+C'
console.log(testExpression(expression, variables, allowedMathFunc));
console.log(testExpression('Sin(B)+Tan(B)+100+Cos(A)+C', ['A','B','C'], ['Sin','Cos','Tan']));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论