帮助正则表达式包含和排除 [英] Help with regex include and exclude

查看:54
本文介绍了帮助正则表达式包含和排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要正则表达式方面的帮助.

I would like some help with regex.

我正在尝试创建一个包含某些字符串并排除某些字符串的表达式.

I'm trying to create an expression that will include certain strings and exclude certain strings.

例如:

我想包含任何包含移动性的 URL http://www.something.com/mobility/

I would like to include any URL containing mobility http://www.something.com/mobility/

但是我想排除任何包含商店 http://www.something.com/store/mobility/

However I would like to exclude any URL containing store http://www.something.com/store/mobility/

仅供参考,我使用了许多关键字.目前我包括这样的 /mobility|enterprise|products/i 但是我发现它无法排除包含其他关键字的链接.

FYI I have many keywords that I'm using to include. Currently I am including like this /mobility|enterprise|products/i however I am not finding it able to exclude links that contain other keywords.

预先感谢您提供的任何帮助和见解.

Thank you in advance for any help and insight you can provide.

_t

推荐答案

可以在一个正则表达式中完成所有这些,但您实际上并不需要这样做.我认为如果您运行两个单独的测试,您会过得更好:一个用于包含规则,另一个用于排除规则.不确定您使用的是哪种语言,因此我将使用 JavaScript 作为示例:

It's possible to do all this in one regex, but you don't really need to. I think you'll have a better time if you run two separate tests: one for your include rules and one for your exclude rules. Not sure what language you're using, so I'll use JavaScript for the 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);
}

如果你真的想用一种模式来做,试试这样的:

/(?=.*\b(mobility|enterprise|products)\b)(?!.*\b(store|foo|bar)\b)(.+)/i

末尾的 i 表示不区分大小写,因此如果您不使用 JavaScript,请使用您的语言的等效项.

The i at the end means case-insensitive, so use your language's equivalent if you're not using JavaScript.

综上所述,根据您对问题的描述,我认为您真正想要的是字符串操作.这是一个例子,再次使用 JS:

All that being said, based on your description of the problem, I think what you REALLY want for this is string manipulation. Here's an example, again using JS:

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;
        }
    }
}

这篇关于帮助正则表达式包含和排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆