模式匹配以获取括号之间的字符串

时间:2015-03-19 07:30:12

标签: javascript regex

我试图在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"}}}]

I am searching for something like this

4 个答案:

答案 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]