看看this answer。
引用:
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.
"""
或者可用的形式(因为JS不能处理多行正则表达式字符串):
var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
可以使用 RegEx.test() 调用
if (!re_valid.test(text)) return null;
第一个匹配项查找有效的单引号字符串。第二个匹配查找有效的双引号字符串,第三个查找不带引号的字符串。
如果您删除单引号匹配,则它几乎 100% 实现了有效的 IETF RFC 4810 规范 CSV 验证器。
注意:它可能是 100%,但我不记得它是否可以处理值中的换行符(我认为 [\S\s] 是用于检查换行符的特定于 javascript 的 hack)。
注意:这是一个仅限 JavaScript 的实现,不能保证 RegEx 源字符串在 PHP 中有效。
如果您打算对 CSV 数据做任何重要的事情,我建议您采用现有的库。如果您正在寻找符合 RFC 的实现,它会变得非常难看。