当且仅当分隔符不被引号包含时,才拆分字符串

4

我需要在JavaScript中编写一个分割函数,将字符串按逗号拆分为数组...但是逗号不应该被引号('")包含。

下面是三个示例以及结果(数组)的展示:

"peanut, butter, jelly"
  -> ["peanut", "butter", "jelly"]

"peanut, 'butter, bread', 'jelly'"
  -> ["peanut", "butter, bread", "jelly"]

'peanut, "butter, bread", "jelly"'
  -> ["peanut", 'butter, bread', "jelly"]

我不能使用JavaScript的split方法的原因是,它在定界符被引号包含时也会进行分割。
我可以通过正则表达式来实现这个功能吗?
关于上下文,我将使用它来拆分从第三个参数传递给您创建的函数的第三个元素中传递的参数,该函数扩展了jQuery的$.expr[':']。通常,给该参数命名为meta,它是一个包含有关筛选器的某些信息的数组。
不管怎样,该数组的第三个元素是一个字符串,其中包含传递给筛选器的参数;并且由于参数以字符串格式存在,因此需要正确拆分它们以进行解析。

你能控制整个集合以确保所有元素都包含在单引号内,并且不会包含任何单引号吗? - Nathan Wheeler
更多关于这个问题的背景信息会很有趣。看起来你正在尝试从一个字符串中解析JavaScript或JSON。即使在解析像这样的数组的最简单情况下,可能有更好的方法来处理它,而不是使用正则表达式和分割。 - Andy Hume
正则表达式并不适用于这个问题,这已经被讨论过很多次了... - dmckee --- ex-moderator kitten
4个回答

3
您所需要的是一个JavaScript CSV解析器。在Google上搜索“JavaScript CSV解析器”,您会得到很多结果,其中许多包含完整的脚本。另请参见JavaScript代码解析CSV数据

仅仅为了严谨起见,对于这个问题,“词法分析器”比“解析器”更合适。 - Thomas Eding

1
var str = 'text, foo, "haha, dude", bar';
var fragments = str.match(/[a-z]+|(['"]).*?\1/g);

更好的是(支持在字符串内部使用转义的"'):

var str = 'text_123 space, foo, "text, here\", dude", bar, \'one, two\', blob';
var fragments = str.match(/[^"', ][^"',]+[^"', ]|(["'])(?:[^\1\\\\]|\\\\.)*\1/g);

// Result:
0: text_123 space
1: foo
2: "text, here\", dude"
3: bar
4: 'one, two'
5: blob

不处理交换的 '" 分隔符,以及非字母字符。 - Jim Garrison
我用一个简单的测试运行了它,输入"a,b",但它返回了null。显然它不能识别少于3个字符的单词。 - Andreas Grech
一些其他的问题:1) \1 在字符类内不作为组引用(它只匹配 1); 2) 在正则表达式中,你只需要使用两个反斜杠来匹配一个字面上的反斜杠,而不是四个; 3) 要在目标字符串中放置反斜线引号,必须在字符串文字中使用 \\",而不是 \"4) 除非原始数据创建者另有说明,否则在 CSV 数据中应将空白视为重要内容(这意味着你的正则表达式的第一部分应该仅为 ["',\s]+)。 - Alan Moore

1

好的,我已经写了一个像凿岩机一样的解决方案(通用代码编写用于其他事情),所以只是为了好玩……

function Lexer () {
  this.setIndex = false;
  this.useNew = false;
  for (var i = 0; i < arguments.length; ++i) {
    var arg = arguments [i];
    if (arg === Lexer.USE_NEW) {
      this.useNew = true;
    }
    else if (arg === Lexer.SET_INDEX) {
      this.setIndex = Lexer.DEFAULT_INDEX;
    }
    else if (arg instanceof Lexer.SET_INDEX) {
      this.setIndex = arg.indexProp;
    }
  }
  this.rules = [];
  this.errorLexeme = null;
}

Lexer.NULL_LEXEME = {};

Lexer.ERROR_LEXEME = { 
  toString: function () {
    return "[object Lexer.ERROR_LEXEME]";
  }
};

Lexer.DEFAULT_INDEX = "index";

Lexer.USE_NEW = {};

Lexer.SET_INDEX = function (indexProp) {
  if ( !(this instanceof arguments.callee)) {
    return new arguments.callee.apply (this, arguments);
  }
  if (indexProp === undefined) {
    indexProp = Lexer.DEFAULT_INDEX;
  }
  this.indexProp = indexProp;
};

(function () {
  var New = (function () {
    var fs = [];
    return function () {
      var f = fs [arguments.length];
      if (f) {
        return f.apply (this, arguments);
      }
      var argStrs = [];
      for (var i = 0; i < arguments.length; ++i) {
        argStrs.push ("a[" + i + "]");
      }
      f = new Function ("var a=arguments;return new this(" + argStrs.join () + ");");
      if (arguments.length < 100) {
        fs [arguments.length] = f;
      }
      return f.apply (this, arguments);
    };
  }) ();

  var flagMap = [
      ["global", "g"]
    , ["ignoreCase", "i"]
    , ["multiline", "m"]
    , ["sticky", "y"]
    ];

  function getFlags (regex) {
    var flags = "";
    for (var i = 0; i < flagMap.length; ++i) {
      if (regex [flagMap [i] [0]]) {
        flags += flagMap [i] [1];
      }
    }
    return flags;
  }

  function not (x) {
    return function (y) {
      return x !== y;
    };
  }

  function Rule (regex, lexeme) {
    if (!regex.global) {
      var flags = "g" + getFlags (regex);
      regex = new RegExp (regex.source, flags);
    }
    this.regex = regex;
    this.lexeme = lexeme;
  }

  Lexer.prototype = {
      constructor: Lexer

    , addRule: function (regex, lexeme) {
        var rule = new Rule (regex, lexeme);
        this.rules.push (rule);
      }

    , setErrorLexeme: function (lexeme) {
        this.errorLexeme = lexeme;
      }

    , runLexeme: function (lexeme, exec) {
        if (typeof lexeme !== "function") {
          return lexeme;
        }
        var args = exec.concat (exec.index, exec.input);
        if (this.useNew) {
          return New.apply (lexeme, args);
        }
        return lexeme.apply (null, args);
      }

    , lex: function (str) {
        var index = 0;
        var lexemes = [];
        if (this.setIndex) {
          lexemes.push = function () {
            for (var i = 0; i < arguments.length; ++i) {
              if (arguments [i]) {
                arguments [i] [this.setIndex] = index;
              }
            }
            return Array.prototype.push.apply (this, arguments);
          };
        }
        while (index < str.length) {
          var bestExec = null;
          var bestRule = null;
          for (var i = 0; i < this.rules.length; ++i) {
            var rule = this.rules [i];
            rule.regex.lastIndex = index;
            var exec = rule.regex.exec (str);
            if (exec) {
              var doUpdate = !bestExec 
                || (exec.index < bestExec.index)
                || (exec.index === bestExec.index && exec [0].length > bestExec [0].length)
                ;
              if (doUpdate) {
                bestExec = exec;
                bestRule = rule;
              }
            }
          }
          if (!bestExec) {
            if (this.errorLexeme) {
              lexemes.push (this.errorLexeme);
              return lexemes.filter (not (Lexer.NULL_LEXEME));
            }
            ++index;
          }
          else {
            if (this.errorLexeme && index !== bestExec.index) {
              lexemes.push (this.errorLexeme);
            }
            var lexeme = this.runLexeme (bestRule.lexeme, bestExec);
            lexemes.push (lexeme);
          }
          index = bestRule.regex.lastIndex;
        }
        return lexemes.filter (not (Lexer.NULL_LEXEME));
      }
  };
}) ();

if (!Array.prototype.filter) {
  Array.prototype.filter = function (fun) {
    var len = this.length >>> 0;
    var res = [];
    var thisp = arguments [1];
    for (var i = 0; i < len; ++i) {
      if (i in this) {
        var val = this [i];
        if (fun.call (thisp, val, i, this)) {
          res.push (val);
        }
      }
    }
    return res;
  };
}

现在要使用代码解决您的问题:

function trim (str) {
  str = str.replace (/^\s+/, "");
  str = str.replace (/\s+$/, "");
  return str;
}

var splitter = new Lexer ();
splitter.setErrorLexeme (Lexer.ERROR_LEXEME);
splitter.addRule (/[^,"]*"[^"]*"[^,"]*/g, trim);
splitter.addRule (/[^,']*'[^']*'[^,']*/g, trim);
splitter.addRule (/[^,"']+/g, trim);
splitter.addRule (/,/g, Lexer.NULL_LEXEME);

var strs = [
    "peanut, butter, jelly"
  , "peanut, 'butter, bread', 'jelly'"
  , 'peanut, "butter, bread", "jelly"'
  ];

// NOTE: I'm lazy here, so I'm using Array.prototype.map, 
//       which isn't supported in all browsers.
var splitStrs = strs.map (function (str) {
  return splitter.lex (str);
});

-1

如果您可以控制输入,以强制字符串将被双引号"包含,并且字符串中的所有元素都将被单引号'包含,并且没有元素可以包含单引号,则可以在, '上进行拆分。如果您无法控制输入,则使用正则表达式对输入进行排序/过滤/拆分与使用正则表达式匹配xhtml(参见:RegEx match open tags except XHTML self-contained tags)一样有用。


我不明白你链接的那个帖子和这个有什么关系。好吧,在这种情况下我不会使用正则表达式,但是在这里面临的问题与尝试使用正则表达式解析(x)html几乎没有任何关系。是因为(x)html的递归性质而无法完成,但这个问题根本不是关于那个的。似乎在每个带有“regex”一词的线程中,都会发布一个链接到(#1732348)的帖子... - Bart Kiers
问题在于,如果您不确定输入可能包含什么内容,那么就没有正则表达式可以正确解析它。 - Nathan Wheeler
我的观点是,帖子 #1732348 与此贴关系不大。而且你不确切知道你的输入是什么,这正是正则表达式要做的:定义可能变化的模式。 - Bart Kiers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接