user4324324
user4324324

Reputation: 559

Pattern match to get string between brackets

I am trying to find whatever string is in between the aggregate() and find(). Below is my code.

var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'

var matchPharse = /((.*))/;
var result = str1.match(matchPharse);
console.log(result); 

I am getting the result always the whole string instead of

[{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}]

I am searching for something like this

Upvotes: 1

Views: 74

Answers (4)

cнŝdk
cнŝdk

Reputation: 32145

Try the following RegEx:

var matchPharse= /\((.*)\)/g;

Matches any sequence between ().

This is a DEMO.

var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /\((.*)\)/;
var result = str1.match(matchPharse);
alert(result); 

Upvotes: 1

vks
vks

Reputation: 67968

((\[.*?\]))

You Should use a non greedy expression.

Upvotes: 1

bozdoz
bozdoz

Reputation: 12860

You just need to escape the outside parentheses. Try:

var matchPharse = /\((.*)\)/;

For just the content inside the parentheses use result[1]

Upvotes: 0

mish
mish

Reputation: 1065

try this pattern instead:

var matchPharse = /((\[.*\]))/;

Upvotes: 1

Related Questions