通过跳过拆分字符在javascript中拆分字符串

时间:2015-04-05 16:32:11

标签: javascript

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"

3 个答案:

答案 0 :(得分:2)

如果你不想像其他答案那样解析,我会分开引用的表达式和逗号:

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"]

答案 1 :(得分:0)

解析分隔符(如引号(或parens,括号等),但出于几个原因而特别是引号)最好使用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
}

这可以扩展为解析单引号字符串和其他分隔符(您必须为非引用分隔符构建堆栈)。我发布了一个修改版本,可以处理Regex to pick commas outside of quotes

中的单引号和双引号

答案 2 :(得分:-1)