简体   繁体   English

从Node.JS中的Javascript正则表达式中获取NULL

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

The following code is part of a Node.js application. 以下代码是Node.js应用程序的一部分。 Am trying to use regular expressions to get the url parts, but with difficulty. 我试图使用正则表达式来获取url部分,但很难。 When it is passed an obviously matching 'req.url' string, where even regex.test(req.url) returns true, am getting back null from regex.match. 当传递一个明显匹配的'req.url'字符串,即使regex.test(req.url)返回true,我也会从regex.match返回null。 Why so? 为什么这样? When I use regex.match() without using regex.test() in front, I get the regex results array OK... But I need to do a regex.test() in the real application. 当我使用regex.match()而不使用前面的regex.test()时,我得到正则表达式结果数组OK ...但我需要在实际应用程序中执行regex.test()。 And isn't it possible/legal to use regex.match() right after regex.test()? 在regex.test()之后立即使用regex.match()是否可行/合法?

For instance, when req.url = "/?format=html&path=/news/crawl/2015/10/01/http---newssite.com--crawl.html" I get a null from regex.match. 例如,当req.url = "/?format=html&path=/news/crawl/2015/10/01/http---newssite.com--crawl.html"我从regex.match得到一个null。 In fact no string ever matches with the following code: 实际上,没有字符串与以下代码匹配:

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');

The reason regexp.exec() fails after calling regexp.test() is because regexp.test() sets the regexp.lastIndex to the end of the string, which is where the last match ended. 调用regexp.test()regexp.exec()失败的原因是因为regexp.test()regexp.lastIndex设置为字符串的末尾,这是最后一个匹配结束的位置。

So when regexp.exec() executes, it tries to start off at regexp.lastIndex (the end of the string), which never matches anything because it's the same string. 因此,当regexp.exec()执行时,它会尝试从regexp.lastIndex (字符串的结尾)开始,它从不匹配任何东西,因为它是相同的字符串。

You can reset this property manually after regexp.test() via regexp.lastIndex = 0; 您可以在regexp.test()通过regexp.lastIndex = 0;手动重置此属性regexp.lastIndex = 0; .

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

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