[英]JavaScript: regex for “split” function to exclude commas and line breaks
I have text file with following structure: 我有以下结构的文本文件:
2013-12-31 15:42,1
2013-12-31 15:45,1
2013-12-31 15:45,0
2013-12-31 16:18,0
2013-12-31 16:18,1
2013-12-31 16:27,1
2013-12-31 16:27,0
2013-12-31 17:11,0
2013-12-31 17:11,1
2013-12-31 18:11,1
2013-12-31 18:11,0
I am importing it by get(): 我通过get()导入它:
$.get('graph_data.txt', function(data){
...}
That is working fine. 很好 Later I am parsing this data to array by: 稍后,我通过以下方式将此数据解析为数组:
var array3 = data.split("\n");
But what I need to do is to split it either by comma or line break. 但是我需要做的是用逗号或换行符将其拆分。 I know that split can get regular expression but all the attempts that I did were unsuccessful: 我知道split可以得到正则表达式,但是我所做的所有尝试均未成功:
.split("[,\\n]");
.split("/,|\s/");
.split("/,|\s/m");
What works for me was to do it in two steps - firstly split by one separator and later by second one: 对我有用的是分两个步骤进行操作-首先由一个分隔符分开,然后由第二个分隔符分开:
var array3 = data.split("\n")[0].split(",");
var array5 = data.split("\n")[1].split(",");
But this is crazy if I have more data in the file. 但是,如果文件中有更多数据,这太疯狂了。
To throw more light on what I want to achieve: I need to get array of coordainates used to draw a chart. 为了进一步阐明我要实现的目标:我需要获取用于绘制图表的coordainate数组。 The first value is date and second is either 0 or 1. 第一个值是日期,第二个值是0或1。
var line=[
['2013-12-31 15:42',1],
['2013-12-31 15:45',1],
['2013-12-31 15:45',0],
['2013-12-31 16:18',0],
['2013-12-31 16:18',1],
['2013-12-31 16:27',1],
['2013-12-31 16:27',0],
['2013-12-31 17:11',0],
['2013-12-31 17:11',1],
['2013-12-31 18:11',1],
['2013-12-31 18:11',0]
];
I am doing that by mapping second string in each pair to int: 我通过将每对中的第二个字符串映射到int来做到这一点:
var a1 = [array3[0], array5[0]];
var a2 = [array3[1], array5[1]];
var line1 = a1.map(function(e,i){ return [e, parseInt(a2[i]) ] });
Do you have an idea how can I deal with mentioned split function to make it work with two separators in one shot? 您是否知道如何处理上述拆分功能,使其一次使用两个分隔符即可?
var data = data.split("\n").map(function (line) {
var line = line.split(",");
return [ line[0], parseInt(line[1], 10) ];
}
console.log(data);
This will give you 这会给你
[
[ '2013-12-31 15:42', 1 ],
[ '2013-12-31 15:45', 1 ],
[ '2013-12-31 15:45', 0 ],
[ '2013-12-31 16:18', 0 ],
..
]
You can't separate by rows and columns in one statement, nor do I see why you should. 您不能在一个语句中按行和列分开,也看不到为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.