How to iterate each character from a string and add a vbcrlf in certain character VB.net

76 views Asked by At

So, i have a text file. The purpose is to Add VBLF (newline) in certain part of string using VB.net. Here the example of the string:

Before (The string don't have any newline caharcter):

{1:F01ABCDIDJAXXXX0001212544}{2:O9001038231020QWERIDJRAXXX00011102422310201038N}{3:{113:0070}}{4::20:94493831555385/900:21:0799102034308001:25:520008000990:32A:231020USD0,:72:/ESETDATE/2310201038+0000/OID/231020ABCDDJAXXXX0001019040/AMNT/10000000000001,12-}

After:

if we see on notepad ++ will look like this open image here

I was think that we need to iterate through each character. Below is my logic:

1.Find character

{4:

in whole string, then replace with {4: + vbLf

  1. Replace regex

For each character with pattern

^:[\d\w]+:

(like :20: ) Then replace with vbLf + originalcharacter

  1. Replace regex

For each character with pattern

/(.*?)/

(like \AMNT\ )

Then replace with vbLf + originalcharacter

If anyone can help to solve this, appreciate it. Thanks

1

There are 1 answers

1
Nick Abbot On BEST ANSWER

Here is one possible solution without using regex:

Sub test()

    Dim YourString As String = "{1:F01ABCDIDJAXXXX0001212544}{2:O9001038231020QWERIDJRAXXX00011102422310201038N}{3:{113:0070}}{4::20:94493831555385/900:21:0799102034308001:25:520008000990:32A:231020USD0,:72:/ESETDATE/2310201038+0000/OID/231020ABCDDJAXXXX0001019040/AMNT/10000000000001,12-}"
    Debug.Print(DoIt(YourString))

End Sub

Function DoIt(sLine As String) As String

    Dim aTemp1() As String
    Dim aTemp2() As String
    Dim aTemp3() As String

    Dim sResult As String
    Dim i As Integer

    Try

        aTemp1 = sLine.Split("{4:")
        aTemp2 = aTemp1(1).Split(":", StringSplitOptions.RemoveEmptyEntries)
        aTemp3 = aTemp2.Last.Split("/", StringSplitOptions.RemoveEmptyEntries)

        '"{1:F01ABCDIDJAXXXX0001212544}{2:O9001038231020QWERIDJRAXXX00011102422310201038N}{3:{113:0070}}{4:" & vbLf
        sResult = aTemp1(0) & "{4:" & vbLf

        '":20:94493831555385/900" & vbLf & ":21:0799102034308001" & vbLf & ":25:520008000990" & vbLf & ":32A:231020USD0," & vbLf
        For i = 0 To aTemp2.Length - 3 Step 2
            sResult &= ":" & aTemp2(i) & ":"
            sResult &= aTemp2(i + 1) & vbLf
        Next

        '":72:"
        sResult &= ":" & aTemp2(i) & ":"

        '/ESETDATE/2310201038+0000" & vbLf & "/OID/231020ABCDDJAXXXX0001019040" & vbLf & "/AMNT/10000000000001,12-}" & vbLf
        For i = 0 To aTemp3.Length - 1 Step 2
            sResult &= "/" & aTemp3(i) & "/" & aTemp3(i + 1) & vbLf
        Next

        'vbLf & "-}"
        sResult = sResult.Replace("-", vbLf & "-") ' <-- You forgot this part

        Return sResult

    Catch ex As Exception
        Return String.Empty
    End Try

End Function