You can do all this in one regex, but you really don't need it. I think it would be better if you run two separate tests: one for your included rules and one for your exception rules. Not sure which language you are using, so I will use JavaScript for an example:
function validate(str) { var required = /\b(mobility|enterprise|products)\b/i; var blocked = /\b(store|foo|bar)\b/i; return required.test(str) && !blocked.test(str); }
If you really want to do this in one template, try something like this:
/(?=.*\b(mobility|enterprise|products)\b)(?!.*\b(store|foo|bar)\b)(.+)/i
i at the end means case insensitive, so use your language if you are not using JavaScript.
All that has been said, based on your description of the problem, I think what you really want for this is string manipulation. Here is an example using JS again:
function validate(str) { var required = ['mobility','enterprise','products']; var blocked = ['store','foo','bar']; var lowercaseStr = str.toLowerCase(); //or just use str if you want case sensitivity for (var i = 0; i < required.length; i++) { if (lowercaseStr.indexOf(required[i]) === -1) { return false; } } for (var j = 0; j < blocked.length; j++) { if (lowercaseStr.indexOf(blocked[j]) !== -1) { return false; } } }
Justin morgan
source share