簡體   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