所以我有一组管道分隔的输入,如下所示:
“787291 | 3224325523” | 37826427 | 37826427 2482472 | 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 | 37826427 2482472 | 2482472 “46284729|46246”| 24682
|"82524| 6846419 | 68247
这里的代码给出了
畸形线异常
我意识到这是由于我的输入中的杂散引用造成的,而且因为我就像正则表达式中的菜鸟,所以我无法在这里使用它(或者我无法)。如果有人有任何想法,将不胜感激。
这是评论中描述的编码过程:
- 读取原始输入文件的所有行,
- 修复错误的行(使用正则表达式或任何其他合适的东西),
- use
TextFieldParser
执行正确输入的解析
-
Join()
创建的输入部分TextFieldParser
using ,
作为分隔符
- 将固定的、重建的输入行保存到最终的输出文件中
我在用着维克托·斯特里比热夫 https://stackoverflow.com/questions/53883750/changing-a-pipe-delimited-file-to-comma-delimited-in-vb-net#comment94614029_53883750正则表达式模式:根据问题的描述,它看起来应该可以工作。
Note:
当然我不知道是否应该使用特定的编码。
在这里,编码是默认的 https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netframework-4.7.2#System_IO_File_WriteAllLines_System_String_System_String___ UTF-8 no-BOM
, 进进出出。
"FaultyInput.txt"
is the 损坏的源文件。
"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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)