Home > Software engineering >  javascript regex negative lookahed doesn't return what I expect
javascript regex negative lookahed doesn't return what I expect

Time:03-20

I want to match if NO end

/(?<=start ). (?!end)/gs

for example in this example I don't want match, what should i used instead of . ?

start 
blah
blah
blah
end

CodePudding user response:

All you have to do is add $ to your pattern and change the lookahead to lookbehind.

Try this: /(?<=start). $(?<!end)/gs

const pattern = /(?<=start). $(?<!end)/gs;
let input1 = `start 
blah
blah
blah
end`;

let input2 = `start 
blah
blah
blah`;

console.log(pattern.test(input1)) // false
console.log(pattern.test(input2)) // true

(?<=start). $(?<!end)/gs

/(?<=start)  lookbehind, checks if the matched chare are 'start'
. $          matches anything till the end of line
(?<!end)     lookbehind, checks if the previously matched chars are not 'end'
/gs          global and single line flags

Test here:https://regex101.com/r/A1fLnt/1

  • Related