Ozgur
Ozgur

Reputation: 1834

Recursive matching with regular expressions in JavaScript

Example string: $${a},{s$${d}$$}$$

I'd like to match $${d}$$ first and replace it some text so the string would become $${a},{sd}$$, then $${a},{sd}$$ will be matched.

Upvotes: 27

Views: 28849

Answers (6)

uingtea
uingtea

Reputation: 6524

You can try \$\${([^\$]*)}\$\$. The [^\$] means do not capture if a captured group contains $.

var re = new RegExp(/\$\${([^\$]*)}\$\$/, 'g'),
  original = '$${a},{s$${d}$$}$$',
  result = original.replace(re, "$1");

console.log('original: ' + original)
console.log('result: ' + result);

Upvotes: 0

Akash Budhia
Akash Budhia

Reputation: 476

I wrote this myself:

String.prototype.replacerec = function (pattern, what) {
    var newstr = this.replace(pattern, what);
    if (newstr == this)
        return newstr;
    return newstr.replace(pattern, what);
};

Usage:

"My text".replacerec(/pattern/g,"what");

P.S: As suggested by lededje, when using this function in production it's good to have a limiting counter to avoid stack overflow.

Upvotes: 5

Vojta
Vojta

Reputation: 23051

In general, regular expressions are not well suited for that kind of problem. It's better to use a state machine.

Upvotes: -2

Orbling
Orbling

Reputation: 20602

Annoyingly, JavaScript does not provide the PCRE recursive parameter (?R), so it is far from easy to deal with the nested issue. It can be done, however.

I won't reproduce code, but if you check out Steve Levithan's blog, he has some good articles on the subject. He should do, and he is probably the leading authority on regular expressions in JavaScript. He wrote XRegExp, which replaces most of the PCRE bits that are missing, and there is even a Match Recursive plugin!

Upvotes: 43

var content = "your string content";
var found = true;
while (found) {
    found = false;
    content = content.replace(/regex/, () => { found = true; return "new value"; });
}

Upvotes: -1

Since you want to do this recursively, you are probably best off doing multiple matches using a loop.

Regex itself is not well suited for recursive-anything.

Upvotes: 0

Related Questions