Home > Blockchain >  Regex: match text between two strings not including my string
Regex: match text between two strings not including my string

Time:06-21

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())(;)

CodePudding user response:

You can use this modified regex:

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

All I have changed is:

Making \.lean a negative look BEHIND

ESCAPING the parentheses.

CodePudding user response:

^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();`));

CodePudding user response:

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

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

Regex demo

  • Related