简体   繁体   中英

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

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—eg "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)
if(string.match(first_expression))
{
    if(!string.match(second_expression))
    {
        //Do something important
    }
}

This should match what you want and not what you don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM