3

The following code is part of a Node.js application. Am trying to use regular expressions to get the url parts, but with difficulty. 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. 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. And isn't it possible/legal to use regex.match() right after regex.test()?

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. 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');
2
  • Either your test string or your regexp is wrong as that regexp does match that test string. It also returns non-null when used with .exec(). Commented Oct 5, 2015 at 4:00
  • Still my begging question remains... Why doesn't a consecutive regex.test and/or regex.match not work... one will match while the other will fail, no matter the ordering. Commented Oct 5, 2015 at 4:33

1 Answer 1

8

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.

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.

You can reset this property manually after regexp.test() via regexp.lastIndex = 0;.

Sign up to request clarification or add additional context in comments.

4 Comments

Just wanted to write that. :)
Or just remove the g option from the regex expression.
This was the answer I needed. Thanks a lot!
I'll try without the /g option also. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.