VB.Net String MID$ Question - New to vb.net

  • Thread starter Thread starter Keith Kowalski
  • Start date Start date
K

Keith Kowalski

I am passing in a string of varied length
Example1: mil2345_23.lst
Example2: mil23456_1.lst
Example3: mil5567_1234.lst

What I need is to parse out all text after the _ (underscore) and before the
..)
From example 1 I need "23" returned
From example2 I need "1" Returned
From Example3 I need "12345" returned

I was think that MID$ would work but I am not sure how to do this.

Thanks in advance for all your help
 
If it always has just one underscore you could do this

Private Function parseFileName(ByVal myString As String) As String
Dim s1 As String() = myString.Split("_"c)
Dim s2 As String() = s1(1).Split("."c)
Return s2(0)
End Function

--Michael
 
Would this be correct?

Dim strFileName As String = "mil2345_23.lst"

Dim ArrBatchNumberPlus As Array = strFileName.Split("_")

Dim strBatchNumber As String = ArrBatchNumberPlus(1).Replace(".lst",
String.Empty)

It seems to work, but I am not sure if this is the correct way to do this.

Keith Kowalski
 
Keith,
In addition to the other comments:

Is there only one "_"?

Is there only one "."?

Do you want the first "_" or the last "_" before the "."?

Do you want the first "." or the last "." after the "_"?

I would use something like:
Private Shared Function GetStuff(ByVal name As String) As String
Dim index As Integer
index = name.LastIndexOf("_"c)
If index <> -1 Then
name = name.Substring(index + 1)
End If
index = name.IndexOf("."c)
If index <> -1 Then
name = name.Substring(0, index)
End If
Return name
End Function

Public Shared Sub Main()
Const Example1 As String = "mil2345_23.lst"
Const Example2 As String = "mil23456_1.lst"
Const Example3 As String = "mil5567_1234.lst"
Const Example4 As String = "mil55671234lst"
Const Example5 As String = "mil55671234.lst"

Debug.WriteLine(GetStuff(Example1), Example1)
Debug.WriteLine(GetStuff(Example2), Example2)
Debug.WriteLine(GetStuff(Example3), Example3)
Debug.WriteLine(GetStuff(Example4), Example4)
Debug.WriteLine(GetStuff(Example5), Example5)
Return
End Sub

You can change the LastIndexOf & IndexOf of as appropriate. The "_"c is a
Char literal, as opposed to "_" which is a String literal.

Also normally I use the functions in System.IO.Path to remove parts of a
path, however I didn't here as you wanted a subpart of the file name...

Hope this helps
Jay
 
Yes there is only one _ and only one .

The code that Raterus shows works beatifully, thatnks for all who replied.

Keith Kowalski
 
Back
Top