通过跳过拆分字符在 javascript 中拆分字符串
Split string in javascript by skipping split character
var str = '"testStr, 10.0 pl",NA,4.6';
var rawLine = str.split(',');
console.log(rawLine[0]);
console.log(rawLine[1]);
console.log(rawLine[2]);
它给出的结果是:
""testStr"
"10.0 pl""
"NA"
我正在寻找以下结果的地方:
"testStr, 10.0 pl"
"NA"
"4.6"
如果您不想像另一个答案所建议的那样解析,我会拆分引用的表达式和逗号:
function split_string_on_commas_outside_quotes(str) {
return str .
// Replace escaped quotes; will put back later.
replace(/''"/g, "__QUOTE__") .
// Split on quoted strings and commas, but keep in results.
// Use feature of split where groups are retained in result.
split(/(".*?"|,)/) .
// Remove empty strings and commas from result.
filter(function(piece) { return piece && piece !== ','; }) .
// Remove quotes at beginning and end of quoted pieces as you want.
map(function(piece) { return piece.replace(/^"|"$/g, '') }) .
// Restore escaped quotes.
map(function(piece) { return piece.replace(/__QUOTE__/g, "'''""); })
;
}
>> var str = '"testS'"tr, 10.0 pl",NA,4.6'
>> split_string_on_commas_outside_quotes(str)
<< ["testS'"tr, 10.0 pl", "NA", "4.6"]
解析引
号等分隔符(或参数、括号等,但出于几个原因尤其是引号(最好使用 CFG 解析器完成,而不是使用正则表达式。但这很容易,并且在 O(n( 时间内完成,这与正则表达式相同,并且比您最终可能用于此类事情的不规则表达式更好(尽管 RE 是本机的(。
function parseStrings(str){
var parse=[], inString=false, escape=0, end=0
for(var c=0; c<str.length; c++) switch(str[c]){
case '''': escape^=1; break
case ',': if(!inString){
parse.push(str.slice(end, c))
end=c+1
}
escape=0
break
case '"': if(!escape) inString=!inString
default: escape=0 // fallthrough from previous case
}
if(inString) throw SyntaxError('expected matching " at the end of the string')
if(end<c) parse.push(str.slice(end, c))
return parse
}
这也可以扩展到解析单引号字符串和其他分隔符(您必须为非引号分隔符构建一个堆栈(。我发布了一个修改版本,该版本在正则表达式中处理单引号和双引号,以选择引号外的逗号
你应该使用正则表达式:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
相关文章:
- 通过跳过拆分字符在 javascript 中拆分字符串
- jQuery字符串使用split()方法在空格后拆分字符串
- Javascript-正则表达式,用于在未转义字符上拆分字符串,例如|,但忽略|
- 如何在JavaScript中按大小写拆分字符串
- 根据上次出现的、和_拆分字符串
- 拆分字符串数组(JavaScript)后未定义
- 在空行上拆分字符串
- 使用Regex拆分字符串,保留分隔符
- 使用jquery或regex,带点但不带点的拆分字符串位于单引号中
- Nashorn和Rhino:使用空白regexp拆分字符串
- Javascript:不使用.split()方法拆分字符串
- 如何使用正则表达式在javascript中拆分字符串
- Javascript在第一个空格上拆分字符串
- 首次出现时拆分字符串
- 如何使用正则表达式(.match())拆分字符串
- 使用正则表达式拆分字符串
- Javascript:拆分字符串,但仅使用 1 个结果
- Angularjs-拆分字符串问题
- angularjs在拆分字符串时解析语法错误
- 基于javascript中的AND OR逻辑拆分字符串