之前有人问过这个问题,但我一直试图在 中找到解决方案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)
最佳答案
[string].split()
方法不接受 regex
在拆分但只是 [char[]]
或 [string[]]
.
你可以这样试试:
$line -split ',(?=(?:[^"]|"[^"]*")*$)'
powershell
-split
接受 regex
用于拆分文本使用 .net 你可以这样做:
[regex]::Split( $line , ',(?=(?:[^"]|"[^"]*")*$)' )
关于regex - 如何用逗号分割字符串忽略双引号中的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927291/