求一个js正则表达式

ssss
  • 522

检索一个json字符串;格式:

var json = '[{"i":"t2","n":"xx","x":"12678","y":"10456","c":"","m":3},{"i":"t3","n":"xx","x":"13678","y":"11456","c":"","m":3},{"i":"t4","n":"xx","x":"18456","y":"13456","c":"","m":3}]';
    //条件11000 < x < 13000, 11000 < y < 13000
    var reg = //g;
    var result = json.match(reg);

对x,y值满足范围的进行匹配,获取x,y所在的字符串对象({...}).

如x的值需要在11000~13000之间,匹配后的结果:

[{"i":"t2","n":"xx","x":"12678","y":"10456","c":"","m":3}]。
回复
阅读 3.3k
4 个回答

试试json.match(/\{[^{]+?\"x\":\"1[12][0-9]{3}\",\"y\":\"1[12][0-9]{3}\",[^}]+?\}/g)?看看我有没有写错

/\{[^{]+? // 排除{,使用惰性匹配
\"x\":\"1[12][0-9]{3}\", // 只匹配 x 从 11000 到 12999的内容
\"y\":\"1[12][0-9]{3}\",[^}]+?\}/g // 作用于全局

没必要用正则啊。js处理json最合适不过了。

var json = '[{"i":"t2","n":"xx","x":"12678","y":"10456","c":"","m":3},{"i":"t3","n":"xx","x":"13678","y":"11456","c":"","m":3},{"i":"t4","n":"xx","x":"18456","y":"13456","c":"","m":3}]';

//条件11000 < x < 13000, 11000 < y < 13000

var data = JSON.parse(json);
var result = []; 
data.forEach(function(item) {
    if(item.x > 11000 && item.x < 13000 && item.y > 11000 && item.y < 13000) {
        console.log(item);
        result.push(item);
    }
});

只是来秀链式写法的...

var data = JSON.parse(json).filter(function(v){return v.x>11000&&v.x>13000&&v.y>11000&&v.y<13000});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏