如果你想用正则表达式来做,这个怎么样?
(?<=^|,)("[^"]*"|[^,]*)(?=,|$)
这匹配逗号分隔的字段,包括逗号出现在 123,"Yes, No" 等带引号的字符串中的可能性。 Regexr for this.
更详细:
(?<=^|,) # Must be preceded by start-of-line or comma
(
"[^"]*"| # A quote, followed by a bunch of non-quotes, followed by quote, OR
[^,]* # OR anything until the next comma
)
(?=,|$) # Must end with comma or end-of-line
使用类似于 Python 的 re.findall() 的东西,它返回字符串中所有不重叠的匹配项(如果重要的话,从左到右工作。)不要将它与您的 re.search() 或 @ 等价物一起使用987654331@ 仅返回找到的第一个匹配项。
(注意:这实际上在 Python 中不起作用,因为后面的 (?<=^|,) 不是固定宽度。Grr。欢迎对此提出建议。)
编辑:使用非捕获组来使用行首或逗号,而不是后视,它适用于 Python。
>>> test_str = '123,456,"String","String, with, commas","Zero-width fields next",,"",nyet,123'
>>> m = re.findall('(?:^|,)("[^"]*"|[^,]*)(?=,|$)',test_str)
>>> m
['123', '456', '"String"', '"String, with, commas"',
'"Zero-width fields next"', '', '""', 'nyet', '123']
编辑 2:Python 的 re.findall(needle, haystack) 的 Ruby equivalent 是 haystack.scan(needle)。