Javascript Reverse Match

Looking at the documents of a RegExp object and could not find a method that does what I want, or I just don't look complicated enough.

Say I have the text:

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

And the RegExp object:

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

Running reg.match(text); will obviously give me such an array:

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

Is there any way to cancel this process? Thus, I give an array with the same number of matching groups as RegExp for the function and return me the text, which will look like this:

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

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

I'm trying to create a plugin system for my code, and part of it entails getting a regular expression from the plugin and using it in several processes, for example. data extraction, restoration of the source text from some data.

Right now I need to make a plugin so that the function that returns the source text is hoping there is a way to do this, so they didn't just need to reuse regexp. I could prototype the user-defined function into the RegExp class and then use it, I just hoped that it already had some kind of process for this.

+6
source share
2 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 if the regular expression functions are used outside of the capture groups (apparently, I have nothing to do with my life :) Even without using the regular expression functions outside the capture groups: how do you restore case insensitivity with the right case?

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

+2
source

It is impossible if regular expression does not match the entire line or does not match completely.

For example, "abc".match(/.(.)/) returns ["ab", "b"] , but does not contain the complete string anywhere, thus losing the last character "c".

But if your regular exprssion works and matches the whole line, for example "abc".match(/.(.*)/) returns ["abc", "bc"] Then you can capture the complete line using myResult[0]

0
source

Source: https://habr.com/ru/post/948154/


All Articles