将字符串分割,而忽略引号内的分隔符引号、字符串、分隔符、而忽略

2023-09-05 03:35:34 作者:贪欢

我使用.NET的String.Split方法,打破了使用逗号一个字符串,但我想忽略双引号括起来的串串。我已阅读,一个

例如,下面的字符串

 水果,10,香蕉,橘子,葡萄
 

我想获得以下

 水果
10
香蕉,橘子,葡萄
 
字符串的分割

目前我得到以下输出

 水果
10
香蕉
 橙子
 葡萄
在这里输入code
 

下面的建议和提供的答案后,这里是我结束了一个样本。 (它的工作对我来说很明显)

 进口Microsoft.VisualBasic.FileIO

昏暗的FileReader作为新TextFieldParser(文件名)

fileReader.TextFieldType = FieldType.Delimited
fileReader.SetDelimiters(,)
fileReader.HasFieldsEnclosedInQuotes = TRUE

虽然fileReader.EndOfData = FALSE


昏暗columnData()作为字符串= fileReader.ReadFields

现场数据处理

结束在
 

解决方案

您最好采用解析器,像那些在评论中提到。这就是说,有可能做到这一点与正则表达式通过以下方式:

 ,(=(?:?[^] *[^] *)* [^] * $)
 

正前瞻((?= ...))确保有偶数个引号提前逗号分割的(即他们要么发生在对,或者是没有的)。

[^] * 匹配非引号字符。

I am using .NET's String.Split method to break up a string using commas, but I want to ignore strings enclosed in double quotes for the string. I have read that a

For example, the string below.

Fruit,10,"Bananas, Oranges, Grapes"

I would like to get the following

Fruit
10
"Bananas, Oranges, Grapes"

Currently I am getting the following output

Fruit
10
"Bananas
 Oranges
 Grapes"
enter code here

After following suggestions and the answers provided, here is a sample of what I ended up with. (It worked for me obviously)

Imports Microsoft.VisualBasic.FileIO

Dim fileReader As New TextFieldParser(fileName)

fileReader.TextFieldType = FieldType.Delimited
fileReader.SetDelimiters(",")
fileReader.HasFieldsEnclosedInQuotes = True

While fileReader.EndOfData = False


Dim columnData() As String = fileReader.ReadFields

' Processing of field data

End While

解决方案

You are better off with a parser, like those mentioned in the comments. That said, it's possible to do it with regex in the following way:

,(?=(?:[^"]*"[^"]*")*[^"]*$)

The positive lookahead ((?= ... )) ensures that there is an even number of quotes ahead of the comma to split on (i.e. either they occur in pairs, or there are none).

[^"]* matches non-quote characters.

 
精彩推荐