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(/,/);
}
坐标列表结果,
["127.518037,37.834511", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518037,37.834511", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518103,37.834808", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "127.518103,37.834808", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
...
有什么想法,帮忙~
最佳答案
尝试拆分:
/[\s,]+/
字符类[\s,]
匹配任何空白字符或逗号,+
告诉它匹配所述类一次或多次。这样,您的分割数组中就不会出现空字符串。
或者分两步进行,但首先在 \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 上进行测试.
关于javascript - 正则表达式,从字符串中提取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5049738/