所以我有一组管道分隔的输入,如下所示:
"787291 | 3224325523" | 37826427 | 2482472 | "46284729|46246" | 24682 | 82524 | 6846419 | 68247
我使用下面给出的代码将它们转换为逗号分隔:
Dim line As String
Dim fields As String()
Using sw As New StreamWriter("c:\test\output.txt")
Using tfp As New FileIO.TextFieldParser("c:\test\test.txt")
tfp.TextFieldType = FileIO.FieldType.Delimited
tfp.Delimiters = New String() {"|"}
tfp.HasFieldsEnclosedInQuotes = True
While Not tfp.EndOfData
fields = tfp.ReadFields
line = String.Join(",", fields)
sw.WriteLine(line)
End While
End Using
End Using
到目前为止一切顺利。它仅考虑引号之外的分隔符并将其更改为逗号分隔符。但是当我输入如下所示的杂散引号时,麻烦就开始了:
"787291 | 3224325523" | 37826427 | 2482472 | "46284729|46246" | 24682 | "82524 | 6846419 | 68247
这里的代码给出
MalformeLineExcpetion
我意识到这是由于我的输入中的杂散引用造成的,而且因为我就像正则表达式中的菜鸟,所以我无法在这里使用它(或者我无法)。如果有人有任何想法,将不胜感激。
最佳答案
这是评论中描述的编码过程:
- 读取原始输入文件的所有行,
- 修复有问题的行(使用正则表达式或任何其他合适的东西),
- 使用
TextFieldParser
执行正确输入的解析 -
Join()
TextFieldParser
创建的输入部分使用,
作为分隔符 - 将固定的、重构的输入行保存到最终的输出文件
我正在使用Wiktor Stribiżew正则表达式模式:根据问题的描述,它看起来应该可以工作。
注意:
当然我不知道是否应该使用特定的编码。
在这里,Encoding is the default <强> UTF-8 no-BOM
,进出。
<强> "FaultyInput.txt"
是损坏的源文件。
<强> "FixedInput.txt"
是包含由正则表达式(希望)修复的输入行的文件。您还可以使用 MemoryStream
.
<强> "FixedOutput.txt"
是最终的CSV
文件,包含逗号分隔的字段和正确的值。
这些文件都在可执行启动路径中读取/写入。
Dim input As List(Of String) = File.ReadAllLines("FaultyInput.txt").ToList()
For line As Integer = 0 To input.Count - 1
input(line) = Regex.Replace(input(line), "(""\b.*?\b"")|""", "$1")
Next
File.WriteAllLines("FixedInput.txt", input)
Dim output As List(Of String) = New List(Of String)
Using tfp As New FileIO.TextFieldParser("FixedInput.txt")
tfp.TextFieldType = FileIO.FieldType.Delimited
tfp.Delimiters = New String() {"|"}
tfp.HasFieldsEnclosedInQuotes = True
While Not tfp.EndOfData
Dim fields As String() = tfp.ReadFields
output.Add(String.Join(",", fields))
End While
End Using
File.WriteAllLines("FixedOutput.txt", output)
'Eventually...
'File.Delete("FixedInput.txt")
关于regex - 在 VB.net 中将管道分隔文件更改为逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53883750/