Regex with exception of particular words

前端 未结 6 1431
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 03:45

I have problem with regex. I need to make regex with an exception of a set of specified words, for example: apple, orange, juice. and given these words, it will match everyt

6条回答
  •  甜味超标
    2021-01-12 04:19

    I noticed that apple-juice should match according to your parameters, but what about apple juice? I'm assuming that if you are validating apple juice you still want it to fail.

    So - lets build a set of characters that count as a "boundary":

    /[^-a-z0-9A-Z_]/        // Will match any character that is  - _ or 
                            // between a-z 0-9 A-Z 
    
    /(?:^|[^-a-z0-9A-Z_])/  // Matches the beginning of the string, or one of those 
                            // non-word characters.
    
    /(?:[^-a-z0-9A-Z_]|$)/  // Matches a non-word or the end of string
    
    /(?:^|[^-a-z0-9A-Z_])(apple|orange|juice)(?:[^-a-z0-9A-Z_]|$)/ 
       // This should >match< apple/orange/juice ONLY when not preceded/followed by another
       // 'non-word' character just negate the result of the test to obtain your desired
       // result.
    

    In most regexp flavors \b counts as a "word boundary" but the standard list of "word characters" doesn't include - so you need to create a custom one. It could match with /\b(apple|orange|juice)\b/ if you weren't trying to catch - as well...

    If you are only testing 'single word' tests you can go with a much simpler:

    /^(apple|orange|juice)$/ // and take the negation of this...
    

提交回复
热议问题