Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Reverse match process

Looking at the RegExp object docs and couldn't find a method that does what I want, or I'm just not looking hard enough.

Say I have text:

var text = "§193:And Some Text§";

And a RegExp object:

var reg = /§([0-9]+):(.*?)§/;

Running reg.match(text); would obviously give me an array like so:

["§193:And Some Text§","193","And Some Text"]

Is there a way to sort of reverse this process? Such that I give an array, with the same number of matching groups that the RegExp has, to a function and gives me back what the text would look like:

var reg = /§([0-9]+)§(.*?)§/;
var data = ["293","Some New Text"];
var text = reg.rmatch(data);

and text would now be §293:Some New Text§

Am trying to make a plugin system for my code, and a part of it entails getting a regexp from the plugin and using it in several processes, e.g. extracting data, reconstituting original text from some data.

Right now I would have to make the plugin provide a function that would return the original text, and was hoping there was a way of making it so they didn't have to by just reusing the regexp some how. I could prototype a custom function onto the RegExp class and then use that, I was just hoping it already had some process to do this.

like image 458
Patrick Evans Avatar asked Jun 26 '13 16:06

Patrick Evans


1 Answers

function rregex(regex, data) {
    var arr = new String(regex).split(/\(.*?\)/);
    if (!(arr instanceof Array) || !(data instanceof Array) ||
        (arr.length != data.length+1)) return false;

    var result = arr[0];
    for(var i=0; i < data.length; i++) {
        result += data[i] + arr[i+1]; 
    }
    return result;
}

var reg = /§([0-9]+):(.*?)§/;
var data = ["293","Some New Text"];

console.log(rregex(reg, data))

result

/§293:Some New Text§/ 

Of course this is fundamentally impossible when regex's features are used outside the capture groups (apparently I have nothing better to do with my life:) Even without regex feature use outside the capture groups: how will you reconstruct a case insensitive match with correct case?

And of course a lot could be done to improve the above code.

like image 191
Lodewijk Bogaards Avatar answered Nov 03 '22 11:11

Lodewijk Bogaards