0

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.

0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

and here is a fiddle of it in action

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.