Han*_*ans 79 javascript regex split
我有以下类型的字符串
var string = "'string, duppi, du', 23, lala"
Run Code Online (Sandbox Code Playgroud)
我想将字符串拆分为每个逗号上的数组,但只有单引号外的逗号.
我无法弄清楚分裂的正确正则表达式......
string.split(/,/)
Run Code Online (Sandbox Code Playgroud)
会给我的
["'string", " duppi", " du'", " 23", " lala"]
Run Code Online (Sandbox Code Playgroud)
但结果应该是:
["string, duppi, du", "23", "lala"]
Run Code Online (Sandbox Code Playgroud)
有没有任何跨浏览器解决方案?
rid*_*ner 193
2014-12-01更新:以下答案仅适用于一种非常特定的CSV格式.正如DG在评论中正确指出的那样,此解决方案不符合RFC 4180的CSV定义,也不适合MS Excel格式.此解决方案简单地演示了如何解析包含混合字符串类型的一个(非标准)CSV输入行,其中字符串可能包含转义引号和逗号.
正如austincheney正确指出的那样,如果你想正确处理可能包含转义字符的带引号的字符串,你真的需要从头到尾解析字符串.此外,OP没有明确定义"CSV字符串"究竟是什么.首先,我们必须定义什么构成有效的CSV字符串及其各个值.
出于本讨论的目的,"CSV字符串"由零个或多个值组成,其中多个值由逗号分隔.每个值可能包括:
规则/注意事项:
'that\'s cool'.\'引用中删除:单引号值.\"中删除双引号值.一种JavaScript函数,用于将有效的CSV字符串(如上所述)转换为字符串值数组.
此解决方案使用的正则表达式很复杂.并且(恕我直言)所有非平凡的正则表达式都应该以自由间隔模式呈现,并带有大量的注释和缩进.不幸的是,JavaScript不允许自由间隔模式.因此,此解决方案实现的正则表达式首先以本机正则表达式语法呈现(使用Python方便的表示:r'''...'''raw-multi-line-string语法).
首先是一个正则表达式,它验证CVS字符串是否满足上述要求:
re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^ # Anchor to start of string.
\s* # Allow whitespace before value.
(?: # Group for value alternatives.
'[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Allow whitespace after value.
(?: # Zero or more additional values
, # Values separated by a comma.
\s* # Allow whitespace before value.
(?: # Group for value alternatives.
'[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Allow whitespace after value.
)* # Zero or more additional values
$ # Anchor to end of string.
"""
Run Code Online (Sandbox Code Playgroud)
如果字符串与上述正则表达式匹配,则该字符串是有效的CSV字符串(根据前面所述的规则),并且可以使用以下正则表达式进行解析.然后使用以下正则表达式匹配CSV字符串中的一个值.它被重复应用,直到找不到更多匹配(并且所有值都已被解析).
re_value = r"""
# Match one value in valid CSV string.
(?!\s*$) # Don't match empty last value.
\s* # Strip whitespace before value.
(?: # Group for value alternatives.
'([^'\\]*(?:\\[\S\s][^'\\]*)*)' # Either $1: Single quoted string,
| "([^"\\]*(?:\\[\S\s][^"\\]*)*)" # or $2: Double quoted string,
| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*) # or $3: Non-comma, non-quote stuff.
) # End group of value alternatives.
\s* # Strip whitespace after value.
(?:,|$) # Field ends on comma or EOS.
"""
Run Code Online (Sandbox Code Playgroud)
请注意,此正则表达式不匹配有一个特殊情况值 - 该值为空时的最后一个值.这个特殊的"空的最后一个值"案例由下面的js函数测试和处理.
// Return array of string values, or NULL if CSV string not well formed.
function CSVtoArray(text) {
var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
// Return NULL if input string is not well formed CSV string.
if (!re_valid.test(text)) return null;
var a = []; // Initialize array to receive values.
text.replace(re_value, // "Walk" the string using replace with callback.
function(m0, m1, m2, m3) {
// Remove backslash from \' in single quoted values.
if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
// Remove backslash from \" in double quoted values.
else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
else if (m3 !== undefined) a.push(m3);
return ''; // Return empty string.
});
// Handle special case of empty last value.
if (/,\s*$/.test(text)) a.push('');
return a;
};
Run Code Online (Sandbox Code Playgroud)
在以下示例中,花括号用于分隔{result strings}.(这有助于可视化前导/尾随空格和零长度字符串.)
// Test 1: Test string from original question.
var test = "'string, duppi, du', 23, lala";
var a = CSVtoArray(test);
/* Array hes 3 elements:
a[0] = {string, duppi, du}
a[1] = {23}
a[2] = {lala} */
Run Code Online (Sandbox Code Playgroud)
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array hes 0 elements: */
Run Code Online (Sandbox Code Playgroud)
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array hes 2 elements:
a[0] = {}
a[1] = {} */
Run Code Online (Sandbox Code Playgroud)
// Test 4: Double quoted CSV string having single quoted values.
var test = "'one','two with escaped \' single quote', 'three, with, commas'";
var a = CSVtoArray(test);
/* Array hes 3 elements:
a[0] = {one}
a[1] = {two with escaped ' single quote}
a[2] = {three, with, commas} */
Run Code Online (Sandbox Code Playgroud)
// Test 5: Single quoted CSV string having double quoted values.
var test = '"one","two with escaped \" double quote", "three, with, commas"';
var a = CSVtoArray(test);
/* Array hes 3 elements:
a[0] = {one}
a[1] = {two with escaped " double quote}
a[2] = {three, with, commas} */
Run Code Online (Sandbox Code Playgroud)
// Test 6: CSV string with whitespace in and around empty and non-empty values.
var test = " one , 'two' , , ' four' ,, 'six ', ' seven ' , ";
var a = CSVtoArray(test);
/* Array hes 8 elements:
a[0] = {one}
a[1] = {two}
a[2] = {}
a[3] = { four}
a[4] = {}
a[5] = {six }
a[6] = { seven }
a[7] = {} */
Run Code Online (Sandbox Code Playgroud)
此解决方案要求CSV字符串为"有效".例如,未加引号的值可能不包含反斜杠或引号,例如以下CSV字符串无效:
var invalid1 = "one, that's me!, escaped \, comma"
Run Code Online (Sandbox Code Playgroud)
这不是真正的限制,因为任何子字符串都可以表示为单引号或双引号.另请注意,此解决方案仅代表一种可能的定义:"逗号分隔值".
编辑次数:2014-05-19:添加了免责声明. 编辑:2014-12-01:将免责声明移至顶部.
nir*_*iry 36
这不解决问题中的字符串,因为它的格式不符合RFC 4180; 可接受的编码是双引号的双引号.以下解决方案可正常使用谷歌电子表格中的CSV文件d/l.
解析单行是错误的.根据RFC 4180字段可能包含CRLF,这将导致任何行读取器中断CSV文件.这是一个解析CSV字符串的更新版本:
'use strict';
function csvToArray(text) {
let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;
for (l of text) {
if ('"' === l) {
if (s && l === p) row[i] += l;
s = !s;
} else if (',' === l && s) l = row[++i] = '';
else if ('\n' === l && s) {
if ('\r' === p) row[i] = row[i].slice(0, -1);
row = ret[++r] = [l = '']; i = 0;
} else row[i] += l;
p = l;
}
return ret;
};
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"\r\n"2nd line one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"';
console.log(csvToArray(test));Run Code Online (Sandbox Code Playgroud)
(单线解决方案)
function CSVtoArray(text) {
let ret = [''], i = 0, p = '', s = true;
for (let l in text) {
l = text[l];
if ('"' === l) {
s = !s;
if ('"' === p) {
ret[i] += '"';
l = '-';
} else if ('' === p)
l = '-';
} else if (s && ',' === l)
l = ret[++i] = '';
else
ret[i] += l;
p = l;
}
return ret;
}
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,five for fun';
console.log(CSVtoArray(test));Run Code Online (Sandbox Code Playgroud)
为了好玩,以下是从阵列创建CSV的方法:
function arrayToCSV(row) {
for (let i in row) {
row[i] = row[i].replace(/"/g, '""');
}
return '"' + row.join('","') + '"';
}
let row = [
"one",
"two with escaped \" double quote",
"three, with, commas",
"four with no quotes (now has)",
"five for fun"
];
let text = arrayToCSV(row);
console.log(text);Run Code Online (Sandbox Code Playgroud)
我喜欢 FakeRainBrigand 的回答,但是它包含一些问题:它不能处理引号和逗号之间的空格,并且不支持 2 个连续的逗号。我尝试编辑他的答案,但我的编辑被显然不理解我的代码的审阅者拒绝了。这是我的 FakeRainBrigand 代码版本。还有一个小提琴:http : //jsfiddle.net/xTezm/46/
String.prototype.splitCSV = function() {
var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
for (var n = 0; n < matches.length; ++n) {
matches[n] = matches[n].trim();
if (matches[n] == ',') matches[n] = '';
}
if (this[0] == ',') matches.unshift("");
return matches;
}
var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));
Run Code Online (Sandbox Code Playgroud)
小智 6
我有一个非常具体的用例,我想将 Google 表格中的单元格复制到我的网络应用程序中。单元格可以包含双引号和换行符。使用复制和粘贴,单元格由制表符分隔,奇数数据的单元格用双引号引起来。我尝试了这个主要的解决方案,链接文章使用正则表达式、Jquery-CSV 和 CSVToArray。 http://papaparse.com/ 是唯一一个开箱即用的。复制和粘贴与带有默认自动检测选项的 Google 表格无缝连接。
人们似乎为此反对 RegEx。为什么?
(\s*'[^']+'|\s*[^,]+)(?=,|$)
Run Code Online (Sandbox Code Playgroud)
这是代码。我也做了一个小提琴。
String.prototype.splitCSV = function(sep) {
var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;
return matches = this.match(regex);
}
var string = "'string, duppi, du', 23, 'string, duppi, du', lala";
console.log( string.splitCSV() );Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
PEG(.js)语法,用于处理http://en.wikipedia.org/wiki/Comma-separated_values中的 RFC 4180示例:
start
= [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }
line
= first:field rest:("," text:field { return text; })*
& { return !!first || rest.length; } // ignore blank lines
{ rest.unshift(first); return rest; }
field
= '"' text:char* '"' { return text.join(''); }
/ text:[^\n\r,]* { return text.join(''); }
char
= '"' '"' { return '"'; }
/ [^"]
Run Code Online (Sandbox Code Playgroud)
在http://jsfiddle.net/knvzk/10或https://pegjs.org/online进行测试.
通过https://gist.github.com/3362830下载生成的解析器.
正则表达式来救援!这几行代码根据 RFC 4180 标准正确处理带有嵌入逗号、引号和换行符的引用字段。
function parseCsv(data, fieldSep, newLine) {
fieldSep = fieldSep || ',';
newLine = newLine || '\n';
const nSep = '\x1D'; const nSepRe = new RegExp(nSep, 'g');
const qSep = '\x1E'; const qSepRe = new RegExp(qSep, 'g');
const cSep = '\x1F'; const cSepRe = new RegExp(cSep, 'g');
const fieldRe = new RegExp('(^|[' + fieldSep + '\\n])"([^"]*(?:""[^"]*)*)"(?=($|[' + fieldSep + '\\n]))', 'g');
return data
.replace(/\r/g, '')
.replace(/\n+$/, '')
.replace(fieldRe, (match, p1, p2) => {
return p1 + p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep)
})
.split(/\n/)
.map(line => {
return line
.split(fieldSep)
.map(cell => cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ','))
});
}
const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ','; // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n'
let grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]
Run Code Online (Sandbox Code Playgroud)
笔记:
\tTSV(制表符分隔值)<br/>用于 HTML 使用parseCsv函数可避免负/正向后查找,例如也适用于 Safari 浏览器。除非另有说明,否则您不需要有限状态机。由于使用临时替换/恢复、捕获组和正向前瞻的函数式编程方法,正则表达式可以正确处理 RFC 4180。
克隆/下载代码:https://github.com/peterthoeny/parse-csv-js
了解有关正则表达式的更多信息: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex
(这不适用于 Safari 浏览器)
function parseCsv(data, fieldSep, newLine) {
fieldSep = fieldSep || ',';
newLine = newLine || '\n';
var nSep = '\x1D';
var qSep = '\x1E';
var cSep = '\x1F';
var nSepRe = new RegExp(nSep, 'g');
var qSepRe = new RegExp(qSep, 'g');
var cSepRe = new RegExp(cSep, 'g');
var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
var grid = [];
data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
}).split(/\n/).forEach(function(line) {
var row = line.split(fieldSep).map(function(cell) {
return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
});
grid.push(row);
});
return grid;
}
const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ','; // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n'
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]
Run Code Online (Sandbox Code Playgroud)
小智 5
我已经多次使用正则表达式,但每次我总是必须重新学习它,这很令人沮丧:-)
所以这是一个非正则表达式的解决方案:
function csvRowToArray(row, delimiter = ',', quoteChar = '"'){
let nStart = 0, nEnd = 0, a=[], nRowLen=row.length, bQuotedValue;
while (nStart <= nRowLen) {
bQuotedValue = (row.charAt(nStart) === quoteChar);
if (bQuotedValue) {
nStart++;
nEnd = row.indexOf(quoteChar + delimiter, nStart)
} else {
nEnd = row.indexOf(delimiter, nStart)
}
if (nEnd < 0) nEnd = nRowLen;
a.push(row.substring(nStart,nEnd));
nStart = nEnd + delimiter.length + (bQuotedValue ? 1 : 0)
}
return a;
}
Run Code Online (Sandbox Code Playgroud)
怎么运行的:
row。nEnd为收盘价。nEnd为下一个分隔符。nStart为nEnd加上分隔符的长度。有时编写自己的小函数比使用库更好。您自己的代码将运行良好并且只占用很小的空间。此外,您可以轻松调整它以满足您自己的需求。
| 归档时间: |
|
| 查看次数: |
99055 次 |
| 最近记录: |