Search code examples
regex

A regular expression to exclude a word/string


I have a regular expression as follows:

^/[a-z0-9]+$

This matches strings such as /hello or /hello123.

However, I would like it to exclude a couple of string values such as /ignoreme and /ignoreme2.

I've tried a few variants but can't seem to get any to work!

My latest feeble attempt was

^/(((?!ignoreme)|(?!ignoreme2))[a-z0-9])+$

Solution

  • Here's yet another way (using a negative look-ahead):

    ^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$
    

    Note: There's only one capturing expression: ([a-z0-9]+).

    Here's a snippet to play around with, using the javaScript regular expression engine:

    var re = /^\/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$/;
    console.log("/hello123 matches?", "/hello123".match(re) !== null);
    console.log("/ignoreme matches?", "/ignoreme".match(re) !== null);