如何用逗号分隔字符串,忽略双引号中的逗号

时间:2013-04-10 13:30:35

标签: regex powershell split

此问题之前已被问过,但我一直在尝试使用 powershell 解决方案但未获得所需的结果。

$line = '1,2,"N",09/04/13,"P09042013ZSD(1,0)","ZSD"'
[string[]] $splitColumns = $line.Split('(,)(?=(?:[^"]|"[^"]*")*$)', [StringSplitOptions]'RemoveEmptyEntries')

当我循环通过我期待的分割值时

1
2
"N"
09/04/13
"P09042013ZSD(1,0)"
"ZSD"

但我正在

1
2
N
09/04/13
P09042013ZSD
1
0
ZSD

我使用http://regexhero.net/tester/(Split)测试了正则表达式并使用ExplicitCapture设置,并返回了所需的结果。

工作解决方案

$RegexOptions = [System.Text.RegularExpressions.RegexOptions]
$csvSplit = '(,)(?=(?:[^"]|"[^"]*")*$)'

$splitColumns = [regex]::Split("StringHere", $csvSplit, $RegexOptions::ExplicitCapture)

1 个答案:

答案 0 :(得分:8)

[string].split()方法在分割时不接受regex,只是[char[]][string[]]

您可以尝试这样:

 $line -split ',(?=(?:[^"]|"[^"]*")*$)' 

powershell -split接受regex分割文字

使用.net可以这样做:

[regex]::Split( $line , ',(?=(?:[^"]|"[^"]*")*$)' )
相关问题