Regular Expression to exclude set of Keywords

I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.


Solution 1:

^(?:(?!boon\.ini|http).)*$\r?\n?

(taken from RegexBuddy's library) will match any line that does not contain boon.ini and/or http. Is that what you wanted?

Solution 2:

An alternative expression that could be used:

^(?!.*IgnoreMe).*$

^ = indicates start of line
$ = indicates the end of the line
(?! Expression) = indicates zero width look ahead negative match on the expression

The ^ at the front is needed, otherwise when evaluated the negative look ahead could start from somewhere within/beyond the 'IgnoreMe' text - and make a match where you don't want it too.

e.g. If you use the regex:

(?!.*IgnoreMe).*$

With the input "Hello IgnoreMe Please", this will will result in something like: "gnoreMe Please" as the negative look ahead finds that there is no complete string 'IgnoreMe' after the 'I'.

Solution 3:

Rather than negating the result within the expression, you should do it in your code. That way, the expression becomes pretty simple.

\b(boon\.ini|http)\b

Would return true if boon.ini or http was anywhere in your string. It won't match words like httpd or httpxyzzy because of the \b, or word boundaries. If you want, you could just remove them and it will match those too. To add more keywords, just add more pipes.

\b(boon\.ini|http|foo|bar)\b

Solution 4:

you might be well served by writing a regex that will succeed when it encounters the words you're looking for, and then invert the condition.

For instance, in perl you'd use:

if (!/boon\.ini|http/) {
    # the string passed!
}

Solution 5:

^[^£]*$

The above expression will restrict only the pound symbol from the string. This will allow all characters except string.