Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude one regular expression from another regular expression

In JavaScript, is it possible to exclude matches of one regular expression (by writing another regular expression)? For example, I'd like to exclude all matches of the regular expression

/(cl|g|cr|d)(own)/ (which matches "clown", "gown", "crown", and "down")

from the regular expression

/(c|g|cl|cr|d)(o(w|u))(n|d)/ (which matches "crown", "clown", "gown", "clod", etc.).

The combined regular expression should match all strings that match the first regular expression, but not the strings that match the second regular expression.

like image 215
Anderson Green Avatar asked Apr 15 '26 22:04

Anderson Green


1 Answers

Well, you could write it like this:

/(?:cl|g|cr|d)o(?:un|wd)|co[wu][nd]/

But more generally you could use a negative lookahead:

/(?!(?:cl|g|cr|d)own)(?:c|g|cl|cr|d)o[wu][nd]/
like image 87
Niet the Dark Absol Avatar answered Apr 17 '26 12:04

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!