js中的正则表达式,匹配模式除了关键字

时间:2014-05-07 16:44:25

标签: javascript regex regex-negation

我试图在js中找到一个正则表达式模式

Any_Function() //match : Any_Function(
butnotthis() //I don't want to match butnotthis(

我有这种模式:/([a-zA-Z_]+\()/ig

并希望有类似的东西 /(not:butnotthis)|([a-zA-Z_]+\()/ig(不要试试这个)

在这里演示: http://regexr.com/38qag

是否可以不匹配关键字?

3 个答案:

答案 0 :(得分:2)

我解释你的问题的方式,你希望能够创建一个被忽略的功能的黑名单。据我所知,你不能用正则表达式做到这一点;但是,你可以用一点JavaScript来做。

我创建了一个JSFiddle:http://jsfiddle.net/DQN79/

var str = "Any_Function();butnotthis();",
    matches = [],
    blacklist = { butnotthis: true };
str.replace(/([a-zA-Z_]+\()/ig, function (match) {
    if (!blacklist[match.substr(0, match.length - 1)])
        matches.push(match);
});
console.log(matches);

在这个例子中,我滥用String#replace()方法,因为它接受将为每个匹配触发的回调。我使用此回调来检查列入黑名单的函数名称 - 如果该函数未列入黑名单,则会将其添加到matches数组中。

我使用黑名单的哈希映射,因为它在编程上更容易,但你也可以使用字符串,数组等。

答案 1 :(得分:0)

这是一个工作版本:

^(?!(butnotthis\())([a-zA-Z_]+\()/ig

具体要在大括号中忽略的函数列表

http://regexr.com/38qb8

对于Javascript:

    var str = "Any_Function();butnotthis();",
        matches = [],
        blacklist = ["butnotthis"];
// Uses filter method of jQuery
        matches = str.match(/([a-zA-Z_]+\()/ig).filter(
        function (e) {
        var flag = false;
        for (var i in blacklist) {
            if (e.indexOf(blacklist[i]) !== 0) flag = true;
        }
        return flag;
    });
    console.log(matches)

jsBin:http://jsbin.com/vevip/1/edit

答案 2 :(得分:0)

您可以在函数和关键字之间建立约定,其中函数应以大写字母开头。在这种情况下,正则表达式将是:

/(^[A-Z][a-zA-z_]+\()/ig