Javascript 正则表达式返回所有事件,我只需要第一个
我不明白为什么这会同时返回字符串Javascript 正则表达式返回所有事件,我只需要第一个,javascript,regex,node.js,Javascript,Regex,Node.js,我不明白为什么这会同时返回字符串/最近的瞬时值:([^]+)/我只需要第一个匹配项 var http = require("http"); var options = { host: 'waterdata.usgs.gov', port: 80, path: '/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400' }; function extr
/最近的瞬时值:([^]+)/
我只需要第一个匹配项
var http = require("http");
var options = {
host: 'waterdata.usgs.gov',
port: 80,
path: '/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400'
};
function extract (body, cb) {
if(!body)
return;
var matches=body.match(/Most recent instantaneous value: ([^ ]+) /);
if(matches)
cb(matches[1]);
}
http.get(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
extract(chunk, function(v){ console.log(v); });
});
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
});
“数据”事件已被激发多次 您可以通过将最后一部分更改为:
http.get(options, function(res) {
var responseText = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
responseText += chunk;
});
res.on('end', function() {
extract(responseText, console.log);
});
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
});
我想,有几个关于
数据的事件。顺便说一句,您可以编写extract(chunk,console.log)代码>