簡體   English   中英

從Node.JS中的Javascript正則表達式中獲取NULL

[英]Getting Back NULL from Javascript Regular Expressions in Node.JS

以下代碼是Node.js應用程序的一部分。 我試圖使用正則表達式來獲取url部分,但很難。 當傳遞一個明顯匹配的'req.url'字符串,即使regex.test(req.url)返回true,我也會從regex.match返回null。 為什么這樣? 當我使用regex.match()而不使用前面的regex.test()時,我得到正則表達式結果數組OK ...但我需要在實際應用程序中執行regex.test()。 在regex.test()之后立即使用regex.match()是否可行/合法?

例如,當req.url = "/?format=html&path=/news/crawl/2015/10/01/http---newssite.com--crawl.html"我從regex.match得到一個null。 實際上,沒有字符串與以下代碼匹配:

http.createServer(function (req, res) {
        if (req.method == 'GET') {
            var readRegex = /\?format=(json|html|txt)&path=([\w.\/_-]+)/g;
            var file_path, regex_results;
            console.log(req.url);
            switch (true) {
                case readRegex.test(req.url):
                    regex_results = readRegex.exec(req.url);
                    if (regex_results !== null) {
                        console.log(regex_results);                        
                    } else {
                        console.log("Error: 'regex_results' is null!");
                    }
                    break;
            }
        } else {
            res.writeHead(503, {'Content-Type': 'application/json'});
            res.end("{'error':'Method not yet implemented!'}");
        }
    }).listen(22000, '127.0.0.1');

調用regexp.test()regexp.exec()失敗的原因是因為regexp.test()regexp.lastIndex設置為字符串的末尾,這是最后一個匹配結束的位置。

因此,當regexp.exec()執行時,它會嘗試從regexp.lastIndex (字符串的結尾)開始,它從不匹配任何東西,因為它是相同的字符串。

您可以在regexp.test()通過regexp.lastIndex = 0;手動重置此屬性regexp.lastIndex = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM