1

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

Community
  • 1
  • 1
user4324324
  • 559
  • 3
  • 7
  • 25

4 Answers4

1

try this pattern instead:

var matchPharse = /((\[.*\]))/;
mish
  • 1,055
  • 10
  • 29
1
((\[.*?\]))

You Should use a non greedy expression.

vks
  • 67,027
  • 10
  • 91
  • 124
1

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); 
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • Please correct me if I am doing something wrong in the below split. Im splitting on }, var str = '{"a": 2000, "b": "sam"},{"c":1,"d":1}' var res = str.split(/(?:\}\,|\,\{)/); console.log(res[0]) //'{"a": 2000, "b": "sam"' - One bracket is missing console.log(res[1]) //'{"c":1,"d":1}' Expecting output res[0] = {"a": 2000, "b": "sam"} – user4324324 Mar 19 '15 at 12:27
  • if you use split() on } the `}` will not count in the splitted strings. – cнŝdk Mar 19 '15 at 13:35
0

You just need to escape the outside parentheses. Try:

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

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

bozdoz
  • 12,550
  • 7
  • 67
  • 96