I'm fairly new to programming and I got tasked this at work. I need to split the text file every time it hits the string characters {1:
and ends with -}
and then create a new text file. See example below:
Original Text file:
{1:F01BOF}{2:I940B}{4:dfdfd :20:06AUG :25:64 -}{1:F01BO}{2:I940{4:dfdfd :20:06AUG2 :25:6412 :64:C200806EUR1748473,62 -}{1:F01}{2:I940XN}{4:fvfddf :20:06AUG81-}
New Text1:
{1:F01BOF}{2:I940B}{4:dfdfd :20:06AUG :25:64 -}
New Text2
{1:F01BO}{2:I940{4:dfdfd :20:06AUG2 :25:6412 :64:C200806EUR1748473,62 -}
New Text3:
{1:F01}{2:I940XN}{4:fvfddf :20:06AUG81-}
I was using the code below but it doesn't seem to pick up the curly bracket character
Set fso = CreateObject("Scripting.FileSystemObject")
data = split(fso.OpenTextFile("C:\JustNeeded.txt").ReadAll, "{1")
For i = 1 To UBound(data)
fso.OpenTextFile("new" & i & ".txt", 2, True).Write "{1" & data(i)
Next
I was reading up on regex, should I be using that instead? Any help would be great thanks.
-}
, so the first element of the split result is not empty.With
blocks to organize the code. "Doing it all on one line" becomes hard to read quickly. Option Explicit
so all variables must be properly declared. This prevents hard-to-debug issues with typos in variable names, using Option Explicit
with all your VB code a really good habit to get into.ForWriting
) is much nicer than using opaque "magic numbers" like 2
..Close
on a file handle is not strictly necessary here, but it's good manners.Improved code:
Option Explicit
Dim FSO, text, parts, i
Const ForReading = 1
Const ForWriting = 2
Set FSO = CreateObject("Scripting.FileSystemObject")
With FSO.OpenTextFile("C:\JustNeeded.txt", ForReading)
text = .ReadAll
.Close
End with
parts = Split(text, "-}")
For i = 0 To UBound(parts) - 1
If Len(parts(i)) > 0 Then
With FSO.OpenTextFile("new" & (i + 1) & ".txt", ForWriting, True)
.Write parts(i) & "-}"
.Close
End With
End If
Next
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.