TAGS :Viewed: 8 - Published at: a few seconds ago
[ Split String in VB.Net but only if meets a certain format ]
I have the following code to split a string but it sometimes splits a word I do not intend to split.
For example it will split "LFMT" but I only want it to split a string with this format "FM123456".
The code is below;
Dim strSplitTAF() = New String() {"TEMPO", "PROB30", "PROB40", "BECMG", "FM"}
For Each strWord As String In strSplitTAF
strTAF = strTAF.Replace(strWord, Environment.NewLine & strWord)
Next
Do you have any ideas?
Thanks in advance.
Answer 1
To check for the right format, use the following condition
If Str1.Length = 8 AndAlso Str1.Substring(0, 2) = "FM" AndAlso IsNumeric(Str1.Substring(2, 6)) Then
'The code goes here
End If
Replace the Str1 with the variable that has the format "FM123456"
EDIT
check if this is what you want
'Test data for strTAF
Dim strTAF As String = "TEMPO Test1 PROB30 Test2 PROB40 Test3 BECMG Test4 FM123456 Test5 LFMT Test6 FM654321 Test7 FM124"
'FM is removed since it will use a specific condition to split the string (FM + 6 numbers)
Dim strSplitTAF() = New String() {"TEMPO", "PROB30", "PROB40", "BECMG"}
For Each strWord As String In strSplitTAF
strTAF = strTAF.Replace(strWord, Environment.NewLine & strWord)
Next
'Removes the new line on the first line (optional)
strTAF = strTAF.Trim
'Finds the index of the first FM in the string
Dim Index As Integer = strTAF.IndexOf("FM")
While Index > -1
'Checks if the index + 8 (FM + 6 numbers) exceeds the length of the strTAF
If Index + 8 <= strTAF.Length Then
'Checks if the string (consecutive 6 chars) after FM is numeric
If IsNumeric(strTAF.Substring(Index + 2, 6)) Then
strTAF = strTAF.Substring(0, Index) & Environment.NewLine & strTAF.Substring(Index)
End If
Else
Exit While
End If
'Gets the new index of FM
Index = strTAF.IndexOf("FM", Index + 8)
End While