Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting out an expression

Let say I have these two examples

  1. (A = 1) and ( B = 2)
  2. (A = 1)(B = 2 ()).

I need a way to get the following array:

  1. [(],[A][=][1],[)],[and],[(],[B],[=],[2],[)]
  2. [(],[A][=][1],[)],[(],[B],[=],[2],[(],,[)][)]

What I tried to do is the following

Find the delimiters using the following function (in this case the delimiters are the space "" and any brackets ( or ) )

 function findExpressionDelimeter (textAreaValue){
    var delimiterPositions = [];
    var bracesDepth = 0;
    var squareBracketsDepth = 0;
    var bracketsDepth = 0;

    for (var i = 0; i < textAreaValue.length; i++) {
        switch (textAreaValue[i]) {
            case '(':
                bracketsDepth++;
                delimiterPositions.push(i);
                break;
            case ')':
                bracketsDepth--;
                delimiterPositions.push(i);
                break;
            case '[':
                squareBracketsDepth++;
                break;
            case ']':
                squareBracketsDepth--;
                break;
            default:
                if (squareBracketsDepth == 0 && textAreaValue[i] == ' ') {
                    delimiterPositions.push(i);
                }
        }
    }
    return delimiterPositions;
}

Then I tried to loop trough the values returned and extract the values using substring. The issue is that when I have a ( or ) I need to get the next substring as well as the bracket. This is where I am stuck.

    function getTextByDelimeter(delimiterPositions, value) {
            var output = [];
            var index = 0;
            var length = 0;
            var string = "";

            for (var j = 0; j < delimiterPositions.length; j++) {

                if (j == 0) {
                    index = 0;
                } else {
                    index = delimiterPositions[j - 1] + 1;
                }

                length = delimiterPositions[j];


                string = value.substring(index, length);
                output.push(string);
            }
            string = value.substring(length, value.length);
            output.push(string);
            return output;
        }

Any help would be appreciated.

like image 372
Moddinu Avatar asked Nov 10 '22 07:11

Moddinu


1 Answers

You could just match the tokens you are interested in:

var str = "(A = 1) and ( B = 2)";
var arr = str.match(/[()]|[^()\s]+/g);

Result:

["(", "A", "=", "1", ")", "and", "(", "B", "=", "2", ")"]

The regex with some comments:

[()]     # match a single character token
|        # or
[^()\s]+ # match everything else except spaces

If you would like to add more single character tokens, like for example a =, just add it to both character classes. Ie: [()=]|[^()=\s]+

like image 101
Qtax Avatar answered Nov 15 '22 02:11

Qtax