Eric
Eric

Reputation: 10646

JS Regex extract data in parenthesis

I am trying to extract data inside $() from a string. My string looks something like that

$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)

Basically there could be anything inside $() and between every $(). But here cannot be any $() inside a $().

This is what I have so far that does not work

var reg = new RegExp('\\$\\(.*(?![\\(])\\'), 'g');
var match = reg.exec(mystring);

Upvotes: 0

Views: 76

Answers (3)

guest271314
guest271314

Reputation: 1

I am trying to extract data inside $() from a string.

You can use .split() with RegExp /\)[^$]+|[$()]/ to split string at ")" followed one or more characters that are not "$" or "$", "(" and ")" characters, use .filter() to return an array with empty string removed

var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)";

var reg = /\)[^$]+|[$()]/;

var res = mystring.split(reg).filter(Boolean);

console.log(res);

Upvotes: 0

akuiper
akuiper

Reputation: 214957

You can try this one \\$\\([^(]*\\):

var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)"

var reg = new RegExp('\\$\\([^(]*\\)', 'g');

console.log(reg.exec(mystring));
console.log(reg.exec(mystring));
console.log(reg.exec(mystring));

You can use match to collect all matches of the regex pattern in the string:

var mystring = "$(123=tr@e:123)124rt12$(=ttre@tre)frg12<>$(rez45)"

var reg = new RegExp('\\$\\([^(]*\\)', 'g');

console.log(mystring.match(reg));

Upvotes: 3

wp78de
wp78de

Reputation: 18950

To capture everything inside $() use a lazy pattern like this: (?:\$\()(.*?)(?:\))

const regex = /(?:\$\()(.*?)(?:\))/g;
const str = `\$(123=tr@e:123)124rt12\$(=ttre@tre)frg12<>\$(rez45)`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

PS: It would be favorable to use positive Lookarounds instead of non-capture groups, but JavaScript only supports Lookaheads.

Upvotes: 3

Related Questions