javascriptreactjsregexwebregex-group

String 'Regex' Validation for below scenario


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

  1. expression should use variables array values
  2. 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.


Solution

  • 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):

    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']));