Julien TASSIN
Julien TASSIN

Reputation: 5212

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)

Upvotes: 0

Views: 54

Answers (1)

Limbo
Limbo

Reputation: 2290

Tested with https://regex101.com

/(db\.[a-z]+\.[a-z]+\(([^)]+)\)(;|$))/i

Upvotes: 2

Related Questions