正则表达式返回所有出现,我只需要第一次出现

时间:2012-04-04 19:01:09

标签: javascript regex node.js

我无法弄清楚为什么这会返回字符串/Most recent instantaneous value: ([^ ]+) /的两次出现我只需要第一次匹配。

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

1 个答案:

答案 0 :(得分:0)

'data'事件被多次触发。

您可以通过将最后一部分更改为:

来解决此问题
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);
});