繁体   English   中英

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

[英]regex in js, match pattern except keywords

我试图在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

是否可以不匹配关键字?

按照我对问题的解释方式,您希望能够创建一个被忽略函数的黑名单。 据我所知,您不能使用正则表达式执行此操作; 但是,您可以使用一些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()方法,因为该方法接受将为每次匹配触发的回调。 我使用此回调来检查列入黑名单的函数名称-如果该函数未列入黑名单,它将被添加到matchs数组中。

我为黑名单使用了哈希表,因为它在编程上更容易,但是您也可以使用字符串,数组等。

这是一个工作版本:

^(?!(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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM