Home > Software engineering >  Can regexp avoid a pattern in JavaScript?
Can regexp avoid a pattern in JavaScript?

Time:06-23

I have an expression in JS to match all the words containing (for example) 'foo ', but I would like to discard those of them who end with some other pattern.

Is there a way to make this in only one regular expression?

example:

myExp = /foo \w*/; /*should add something to avoid ending with 'ba r'*/

myExp.matchAll('boo, fo, food, foobaaar, foobr');

should result in ["food", "foobr"] not including 'foobaaar'

CodePudding user response:

You want to use a negative lookahead like (?!not_this), of course replace not_this with the appropriate pattern to exclude using word-break characters \b, or whatever fits your logic.

let myExp = /\bfoo (?!\w*ba r\b)\w*/g;

console.log(...' boo fo food foobaaar foobr foobaardd boofoo foodbar '.matchAll(myExp));

CodePudding user response:

You can use negative look ahead. To exclude cases where ba r is not the ending, use \b in that look ahead.

let myExp = /foo (?!\w*ba r\b)\w*/g;
let input = 'boo, fo, food, foobaaar, foobr, foobaardd';

console.log(...input.match(myExp));

  • Related