如何用逗号分割字符串忽略双引​​号中的逗号 [英] How to split a string by comma ignoring comma in double quotes

查看:58
本文介绍了如何用逗号分割字符串忽略双引​​号中的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前有人问过这个问题,但我一直在尝试在 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 , ',(?=(?:[^"]|"[^"]*")*$)' )

这篇关于如何用逗号分割字符串忽略双引​​号中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆