Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
Ozgur Avatar asked Dec 11 '10 00:12

Ozgur


People also ask

Can regular expressions be recursive?

The regex must match at least one character before the next recursion, so that it will actually advance through the string. The regex also needs at least one alternative that does not recurse, or the recursion itself must be optional, to allow the recursion to stop at some point.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do you match a regular expression?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

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, he is probably the leading authority on RegExp in JS. He wrote XRegExp, which replaces most of the PCRE bits that are missing, there is even a Match Recursive plugin!

like image 141
Orbling Avatar answered Oct 16 '22 10:10

Orbling


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.

like image 33
Akash Budhia Avatar answered Oct 16 '22 10:10

Akash Budhia