Finding a js regular expression

93 2

Retrieve a json string; format:

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

Match the range of x, y, and get the string object ({...}) of x, y.

If the value of x needs to be between 11000 ~ 13000, the result follows:

[{"i":"t2","n":"xx","x":"12678","y":"10456","c":"","m":3}]。
4 Answers

63 3

Try it. json.match(/{[^{]+?"x":"1[12][0-9]{3}","y":"1[12][0-9]{3}",[^}]+?}/g) see if I've any mistakes.

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

It isn't necessary to use regular rules. Js handles json, but it's all right.

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