正規表現でやりたいのなら、これはどうですか?
(?<=^|,)("[^"]*"|[^,]*)(?=,|$)
これは、カンマで区切られたフィールドに一致します。これには、。のような引用符で囲まれた文字列内にコンマが表示される可能性が含まれます123,"Yes, No"
。このための正規表現。
もっと詳しく:
(?<=^|,) # 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()
またはre.match()
、最初に見つかった一致のみを返すものと同等のものと一緒に使用しないでください。
(注:後読み(?<=^|,)
が固定幅ではないため、これは実際には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に相当するRubyre.findall(needle, haystack)
はhaystack.scan(needle)
です。