我需要从导入的csv末尾删除一些冗余的'\ n',然后才将这些行分成一个数组(否则我会得到额外的空行)。
public function parseCSV(data:String):Array {
//something to strip linebreaks, \n and \r from end of array
var lines : Array = data.split ( /\R/ );
var preamble : Array = lines.splice(0,trashLength);
var keyArray : Array = lines.splice ( 0, 1 )[0].split ( "," );
var assocArray : Array = [];
for each (var line:String in lines)
{
var valArray : Array = line.split ( "," );
var assoc : Object = {};
for (var i : int = 0; i < keyArray.length; i++)
{
var key : String = keyArray[i];
if (key != null && key != "") assoc[key] = valArray[i];
}
assocArray.push ( assoc );
}
return assocArray;
}
答案 0 :(得分:6)
// normalize line endings to \n, because \r is not recognized as "end of line"
data = data.replace (/\s*\R/g, "\n");
// remove leading and trailing whitespace
data = data.replace (/^\s*|[\t ]+$/gm, "");
答案 1 :(得分:0)
我发现替换仅适用于主题字符串中目标的第一次出现。您可以尝试使用数组拆分/连接。
public static function removeLineBreaks( s:String ) : String
{
return s.split("\r").join("\n");
}
如果您不想使用分隔符,请将“\ n”替换为“”。