RainingChain
RainingChain

Reputation: 7762

Regex: Replace String inside Pattern for Return Value of Function

Input: "some random text [[specialthing]] blah blah"

Output: "some random text ANOTHERTEXT blah blah"


Goal:

Replace [[specialthing]] by what myFunction('specialthing'); will return.

I already got a function that does exactly this without Regex but I was wondering if there would be an easier/better way to do that.

My code:

    data = "some random text [[specialthing]] blah blah";
    for(var i = 0 ; i < data.length ; i++){
        if(data[i] == '[' && data[i+1] == '['){
            var start = i;
            for(var j = start; j < data.length ; j++){
                if(data[j] == ']' && data[j+1] == ']'){
                    var strInBracket = data.slice(start+2,j);
                    var newStr = myFunction(strInBracket);
                    data = data.replace('\[\[' + strInBracket + '\]\]',newStr);
                }
            }
        }
    }

Solution:

    data = "some random text [[specialthing]] blah blah";

    var strInBracket = data.match(/([^\[]*)(..[^\]]*..)(.*)/)[2];
    var newStr = myFunction(strInBracket.slice(2,-2));
    data = data.replace(strInBracket,newStr);

I'm using javascript.

The solution doesn't need to be a regex.

Upvotes: 0

Views: 105

Answers (3)

jshanley
jshanley

Reputation: 9128

Here's a working javascript version of the regex you want:

/(.*?)\[\[(.*?)\]\](.*)/

and here is a fiddle of it in action

Upvotes: 1

ThorSummoner
ThorSummoner

Reputation: 18159

regex in this case is more or less designed to do what you want. Writing the logic to do the string replace manually for your pattern would be a lot of work comparatively, a lot of index math and such that regex makes unnecessary to do manually.

Upvotes: 0

sshashank124
sshashank124

Reputation: 32189

You could match the following regex as:

([^\[]*)(..[^\]]*..)(.*)

and then replace with:

'$1'+myFunction($2)+'$3' //this is pseudocode and not actual code

Demo: http://regex101.com/r/iC0pK1

Upvotes: 1

Related Questions