以下代码是Node.js应用程序的一部分。我试图使用正则表达式来获取url部分,但有困难。当它传递一个明显匹配的'req.url'字符串时,即使regex.test(req.url)返回true,也会从regex.match返回null。为什么这样?当我在前面使用regex.match()而不使用regex.test()时,我得到了正则表达式结果数组OK。但是我需要在真正的应用程序中执行regex.test()。在regex.test()之后使用regex.match()是不是可能/合法?从Node.JS的Javascript正则表达式中取回NULL
例如,当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');
您的测试字符串或您的正则表达式是错误的,因为正则表达式[*会匹配*](https://regex101.com/r/zD9qO6/1)测试字符串。与'.exec()'一起使用时,它也返回非null值。 – mscdex
还有我的乞讨问题仍然存在...... 为什么连续的regex.test和/或regex.match不能正常工作......一个会匹配,另一个会失败,无论顺序如何。 – user3607612