的JavaScript, 我想使用正则表达式从字符串中提取坐标。 这是我的字符串,包括空格和新行,
127.518037,37.834511
127.518037,37.834511
127.518103,37.834808
127.518103,37.834808
127.518169,37.835209
127.518169,37.835209
127.518147,37.835558
127.518147,37.835558
127.518059,37.835750
127.518059,37.835750
127.518081,37.835976
127.518081,37.835976
127.518411,37.836412
127.518411,37.836412
127.518697,37.836761
127.518697,37.836761
127.518719,37.837198
127.518719,37.837198
127.518741,37.837669
127.518741,37.837669
127.518477,37.838087
127.518477,37.838087
127.518433,37.838401
127.518433,37.838401
我试过这样,但结果不是我想要的。
var coords = item.split(/\s/);
for( item in coords){
coords_list = item.split(/,/);
}
coords_list结果,
["127.518037,37.834511", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518037,37.834511", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518103,37.834808", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518103,37.834808", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
...
任何想法,帮助〜
答案 0 :(得分:0)
尝试拆分:
/[\s,]+/
字符类[\s,]
匹配任何空格字符或逗号,+
告诉它与所述类匹配一次或多次。这样你就不会在split数组中得到空字符串了。
或者分两步完成,但先在\s+
而不是\s
分开:
以下内容:
var text =
" 127.518037,37.834511\n" +
" 127.518037,37.834511\n" +
" 127.518103,37.834808\n" +
" 127.518103,37.834808\n" +
" 127.518169,37.835209\n" +
" 127.518169,37.835209\n" +
" 127.518147,37.835558\n" +
" 127.518147,37.835558\n" +
" 127.518059,37.835750\n" +
" 127.518059,37.835750\n" +
" 127.518081,37.835976\n" +
" 127.518081,37.835976\n" +
" 127.518411,37.836412\n" +
" 127.518411,37.836412\n" +
" 127.518697,37.836761\n" +
" 127.518697,37.836761\n" +
" 127.518719,37.837198\n" +
" 127.518719,37.837198\n" +
" 127.518741,37.837669\n" +
" 127.518741,37.837669\n" +
" 127.518477,37.838087\n" +
" 127.518477,37.838087\n" +
" 127.518433,37.838401\n" +
" 127.518433,37.838401";
var coords = text.split(/\s+/);
for(item in coords){
var coords_list = coords[item].split(/,/);
print(coords_list);
}
将打印:
127.518037,37.834511
127.518037,37.834511
127.518103,37.834808
127.518103,37.834808
127.518169,37.835209
127.518169,37.835209
127.518147,37.835558
127.518147,37.835558
127.518059,37.835750
127.518059,37.835750
127.518081,37.835976
127.518081,37.835976
127.518411,37.836412
127.518411,37.836412
127.518697,37.836761
127.518697,37.836761
127.518719,37.837198
127.518719,37.837198
127.518741,37.837669
127.518741,37.837669
127.518477,37.838087
127.518477,37.838087
127.518433,37.838401
127.518433,37.838401
可以在IDEone上进行测试。