我试图在aggregate()和find()之间找到任何字符串。以下是我的代码。
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);
我得到的结果总是整个字符串而不是
[{$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"}}}]
答案 0 :(得分:1)
尝试这种模式:
var matchPharse = /((\[.*\]))/;
答案 1 :(得分:1)
((\[.*?\]))
您应该使用non greedy
表达式。
答案 2 :(得分:1)
尝试以下RegEx:
var matchPharse= /\((.*)\)/g;
匹配()
之间的任何序列。
这是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);

答案 3 :(得分:0)
你只需要逃避外面的括号。尝试:
var matchPharse = /\((.*)\)/;
仅对括号内的内容使用result[1]