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');
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;.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With