简体   繁体   中英

Regexp matching the smallest possible group

I'm a bit lost with greedy / non-greedy regexp

I want a regexp that will match the smallest set possible of a mongodb command.

A mongodb command has this format : db.collection.command(params)

I can have multiples commands separated by ";" and / or whitespaces ending or not with ";".

Exemple :

db.collection.command(params);db.collection.command(params2) // the regexp must returns db.collection.command(params);
db.collection.command(params);db.collection.command(params2); // the regexp must returns db.collection.command(params); too

I tried a lot of things but I didn't find a way to match all my cases.

So far the best regexp I found is :

const commandRegexp = "(db\\.?\\w*?\\.\\w*\\([^]*\\))?;";
const regexp = new RegExp(`${commandRegexp}`);

But it does not handle this cases :

db.collection.command(params);db.collection.command(params2); // the regexp must returns db.collection.command(params); too

The regexp returns db.collection.command(params);db.collection.command(params2); , the whole text.

I need a regexp that will handle all of these :

db.collection.command(params) // the regexp must returns db.collection.command(params)
db.collection.command(params);foobar // the regexp must returns db.collection.command(params)
db.collection.command(params); // the regexp must returns db.collection.command(params);
db.collection.command(params);db.collection.command(params2) // the regexp must returns db.collection.command(params)
db.collection.command(params);db.collection.command(params2); // the regexp must returns db.collection.command(params)

经过https://regex101.com测试

/(db\\.[az]+\\.[az]+\\(([^)]+)\\)(;|$))/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM