问题描述
以前有人问过这个问题,但我一直在尝试在 powershell 中找到解决方案,但没有得到预期的结果.
This question has been asked before but I have been trying to work a solution in powershell but am not getting the desired results.
$line = '1,2,"N",09/04/13,"P09042013ZSD(1,0)","ZSD"'
[string[]] $splitColumns = $line.Split('(,)(?=(?:[^"]|"[^"]*")*$)', [StringSplitOptions]'RemoveEmptyEntries')
当我循环我期望的分割值时
When I loop though the split values I am expecting
1
2
"N"
09/04/13
"P09042013ZSD(1,0)"
"ZSD"
但是我得到了
1
2
N
09/04/13
P09042013ZSD
1
0
ZSD
我已经使用 http://regexhero.net/tester/(拆分)和 ExplicitCapture 测试了正则表达式设置并返回所需的结果.
I have tested the regex using http://regexhero.net/tester/ (Split) with ExplicitCapture set and it returns the desired results.
可行的解决方案
$RegexOptions = [System.Text.RegularExpressions.RegexOptions]
$csvSplit = '(,)(?=(?:[^"]|"[^"]*")*$)'
$splitColumns = [regex]::Split("StringHere", $csvSplit, $RegexOptions::ExplicitCapture)
推荐答案
[string].split()
方法在 split 时不接受 regex
而只接受 [char[]]
或 [string[]]
.
[string].split()
method doesn't accept regex
on split but just [char[]]
or [string[]]
.
你可以这样试试:
$line -split ',(?=(?:[^"]|"[^"]*")*$)'
powershell -split
接受 regex
用于拆分文本
powershell -split
accept regex
for splitting text
使用 .net 你可以这样做:
Using .net you can do it like this:
[regex]::Split( $line , ',(?=(?:[^"]|"[^"]*")*$)' )
这篇关于如何用逗号分割字符串忽略双引号中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!