Conor O'Brien
Conor O'Brien

Reputation: 1027

Splitting an array based on entries in another array

I am working on a JavaScript code that will decompose a RegExp into its base components and give a small explanation as to what it does.

My general idea is to split the input string (as a RegExp) into entries from another array.

My current code:

function interpret(regex){
    var r = regex + "";
    r = r.split("/");
    body = r[1];
    flags = r[2];
    var classes     = [".","\w","\d","\s","\W","\D","\S","[","]"];
    var classdefs   = ["any non-newline character","any word (digit or letter)","any digit (characters 0-9)","any whitespace character","any non-word (non-digit and non-letter)","any non-digit (not characters 0-9)","open matchset","close matchset"];
    var quantifiers = ["*","+","?",
                        /{(\d+)}/g,         // a{n} 
                        /{(\d+),}/g,        // a{n,}
                        /{(\d+),(\d+)}/g,   // a{n,m}
                        /[+*?]\?/g          // a<quant>? - lazy quantification
                      ];
    var quantDefs   = ["repeated 0 or more times","repeated 1 or more times","repeated once or not at all","repeated exactly $1 time","repeated $1 or more times","repeated between $1 and $2 times"];
    var escaped     = ["\t","\n","\r","\.","\*","\\","\^","\?","\|"];
    var escapedDefs = ["a tab","a linefeed","a carriage return","a period","an asterisk","a backslash","a carot","a question mark","a vertical bar"];

    // code to split r based on entries in classes, quantifiers, and escaped.
}

Ideally, this function (lets call it splitR) will return outputs something like this:

> splitR("hello",["he","l"]);
["he", "l", "l", "o"]
> splitR("hello",["he"]);
["he", "llo"]
> splitR("hello",["he","o"]);
["he", "ll", "o"];
> splitR("5 is the square root of 25",[/\d+/g,/\w{3,}/g,"of"]);
["5", " is ", "the", " ", "square", " ", "root", " ", "of", " ", "25"]

Clearly defined, the splitR function should, in the context of the interpret function, take a RegExp and split it into its base components; e.g. \d+[0-9]\w*? should split into ["\d", "+", "[", "0-9", "]", "\w", "*", "?"]. These components are defined separately in other arrays, using a variety of RegExps (e.g. /{(\d+)}/g to find a{n}) and strings (e.g. ".").

Truly, I am stumped as to the definition of splitR. Any help is appreciated!

Upvotes: 0

Views: 251

Answers (1)

This will split a regex in parts, and populate a second array with description of the parts. It will skip unexpected characters, but there's no real regex syntax checking, i.e. if you start a range and don't end it, the script will not complain. I took the liberty of adding some things that were missing from your lists, like grouping brackets, start and end anchors...

function interpret(regex)
{
    var body = regex.source;
    var flags = (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "");
    var classes     = [/^\w\-\w/,/^\./,/^\\w/,/^\\d/,/^\\s/,/^\\W/,/^\\D/,/^\\S/,/^\[/,/^\]/,/^\(/,/^\)/,/^\^/,/^\$/,/^\|/];
    var classDefs   = ["character range","any non-newline character","any word (digit or letter)","any digit (characters 0-9)","any whitespace character","any non-word (non-digit and non-letter)","any non-digit (not characters 0-9)","any non-whitespace character","open matchset","close matchset","open group","close group","start anchor or negation","end anchor","alternative"];
    var quantifiers = [/^[+*?]\?/,/^\*/,/^\+/,/^\?/,/^{(\d+)}/,/^{(\d+),}/,/^{(\d+),(\d+)}/];
    var quantDefs   = ["lazy quantification","repeated 0 or more times","repeated 1 or more times","repeated once or not at all","repeated exactly $1 time","repeated $1 or more times","repeated between $1 and $2 times"];
    var escaped     = [/^\\t/,/^\\n/,/^\\r/,/^\\\./,/^\\\*/,/^\\\+/,/^\\\-/,/^\\\\/,/^\\\^/,/^\\\$/,/^\\\?/,/^\\\|/,/^\\\[/,/^\\\]/,/^\\\(/,/^\\\)/,/^\\\{/,/^\\\}/];
    var escapedDefs = ["a tab","a linefeed","a carriage return","a period","an asterisk","a plus","a minus","a backslash","a caret","a dollar sign","a question mark","a vertical bar","a square bracket","a square bracket","a bracket","a bracket","a curly bracket","a curly bracket"];
    var literal     = [/^[^\.\\\[\]\(\)\^\$\|\*\+\-\?\{\}]+/];
    var literalDefs = ["literal text"];
    var regs = classes.concat(quantifiers,escaped,literal);
    var defs = classDefs.concat(quantDefs,escapedDefs,literalDefs);
    var reglist = [];
    var deflist = [];

    while (body.length)
    {
        var found = false;
        var chunk = null;

        for (var i = 0; i < regs.length; i++)
        {
            chunk = body.match(regs[i]);

            if (chunk)
            {
                reglist.push(chunk[0]);
                deflist.push(defs[i]);
                body = body.substr(chunk[0].length);
                found = true;
                break;
            }
        }

        if (!found)
        {
            body = body.substr(1);	// skip unexpected character
        }
    }

    console.log(regex.source);
    console.log(reglist);
    console.log(deflist);
    alert("see console for output");
}

var x = new RegExp("^[a-z0-9]\\^.\\.\\w\\d\\s\\W\\D\\S+(te|\\|st)*\\*\\n+\\+\\-\\}(\\W?\\?\\s{1,3})\\\\*?a{3}b{4,}c{}\\r\\t\\$$", "ig");
interpret(x);

Upvotes: 1

Related Questions