Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript match one regex, but not another

How can I find all words in string which
match one expression:

/[a-zA-Z]{4,}/

but do not match another one:

/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/

Something like pseudocode:

string.match( (first_expression) && ( ! second_expression) )
like image 538
kriskodzi Avatar asked Nov 26 '25 06:11

kriskodzi


1 Answers

You could just do this:

string.match(/[a-zA-Z]{4,}/) && !string.match(/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/)

But if you'd like to combine the patterns, you can use a negative lookahead ((?!...)), like this:

string.match(/^(?!.*\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b).*[a-zA-Z]{4,}.*$/)

But this will reject the whole string if it finds the second pattern—e.g."fooz barz" will return null.

To ensure the words you find do not match the other pattern, try this:

string.match(/\b(?![a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b)[a-zA-Z]{4,}\b/)

In this case, "fooz barz" will return "barz".

Note that this can be cleaned up a bit by using the case insensitive flag (i):

string.match(/\b(?![a-z]([a-z])\1+[a-z]\b)[a-z]{4,}\b/i)
like image 105
p.s.w.g Avatar answered Nov 28 '25 18:11

p.s.w.g



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!