Dev01
Dev01

Reputation: 14159

Regex: match text between two strings not including my string

I have a string and want to match:

await Listing.find({
    Test: 1
});

But don’t want to match it if it ends with .lean();

await Listing.find({
    Test: 1
}).lean();

I have this regex but it’s not working: (?<=await)([\S\s]*?)(?!.+\.lean())(;)

Upvotes: 0

Views: 568

Answers (4)

Dev01
Dev01

Reputation: 14159

I ended up using this in vscode to find all mongoose queries that don't use lean so that I can increase the speed of queries and reduce memory footprint:

await (.*)find(([^;]|\n)*?)(?<!.\.lean\(\))(;)

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163457

If you want to stay between a single opening and closing parenthesis, you don't need any assertion:

\bawait\s[^()]*\([^()]*\);

Regex demo

Upvotes: 1

Artyom Vancyan
Artyom Vancyan

Reputation: 5390

^await(?:(?!\.lean\(\)).)*;$

Short Explanation

  • ^await String starts with await
  • (?:(?!\.lean\(\)).)*; Contains anything except .lean() till the last ; colon

Also, see the regex demo

JavaScript Example

let regex = /^await(?:(?!\.lean\(\)).)*;$/s;

console.log(regex.test(`await Listing.find({
    Test: 1
});`));

console.log(regex.test(`await Listing.find({
    Test: 1
}).lean();`));

Upvotes: 1

Poul Bak
Poul Bak

Reputation: 10930

You can use this modified regex:

(?<=await)([\S\s]*?)(?<!.+\.lean\(\))(;)

All I have changed is:

Making \.lean a negative look BEHIND

ESCAPING the parentheses.

Upvotes: 1

Related Questions