我想为表行字符串返回一个数组,如下所示:
'31 Chicken 2013 "Chi cken" 12.345 ****'到数组:["Chicken", 2013, "Chi cken", 12.345, null]
有什么帮助吗?
(链接到更完整的格式信息:Format.pdf)
发布于 2016-06-14 00:52:54
我采纳了克隆哈姆的一些建议和这个答案的一个准则。无法理解如何从添加到匹配字符串中获取引号。
var str = '31 Chicken 2013 "Chi cken" 12.345 ****';
console.log(str);
var tmp = str.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g);
console.log(tmp);
var n;
tmp.shift();
for (i = 0; i < tmp.length; i++) {
str = tmp[i];
if (str === "****") {
tmp[i] = null;
}
else if (str.startsWith('"')) {
n = str.lastIndexOf('"');
tmp[i] = str.slice(1,n);
}
else {
n = Number(str);
if(isNaN(n)){
//console.log(str + " NaN")
}
else tmp[i] = n;
}
}
console.log(tmp);发布于 2016-06-13 21:25:59
我会编写一个解析器,它涵盖了您的示例。
工作示例:JSFiddle
for (i = 0; i < tmp.length; i++) {
if (i == 0) continue;
else if (tmp[i] === "****") {
output.push("null");
continue;
}
else if (tmp[i].startsWith('"')) {
output.push(tmp[i] + ' ' + tmp[i + 1]);
i++;
continue;
}
else {
output.push(tmp[i]);
}
}发布于 2016-06-13 21:38:04
下面是六个匹配项的正则表达式,然后您可以忘记项[0]并将最后一个项转换为null (时*)
[0-9\.0-9]+|[a-zA-Z0-9]+|\"[a-zA-Z0-9 ]+\"|\*\*\*\*https://stackoverflow.com/questions/37799049
复制相似问题