String problem (VB2005)

nbrege

Freshman
Joined
Jan 12, 2006
Messages
34
I have a string that represents a part number. The part number is always a 5 or 6 digit number, such as "35292" or "105468". Optionally, the 5 digit part numbers could have a suffix such as "37023-BF". I am trying to find a way to get just the numerical portion of the part number string whether it is 5 or 6 digits & has a suffix or not. The first character of the suffix will always be a dash ("-"), if that helps any. I have tried the parse & convert methods but they error out on the strings with suffixes. Can anyone provide me with a solution to this problem? Thanks...
 
Last edited:
Visual Basic:
Imports System.Text.RegularExpressions
...
...
Dim partPattern As New Regex("^\\d+", RegexOptions.Compiled)
...
Integer.TryParse(partPattern.Match(partId).Value, partNumber)
 
One way.

Since you are using VB I suggest Split-function.

Visual Basic:
        MsgBox(Split("35292", "-")(0))
        MsgBox(Split("105468", "-")(0))
        MsgBox(Split("37023-BF", "-")(0))
 
Also...

In case you wanna know more about string parsing in VB, which is quite simple...

You can use Split also like this:
Visual Basic:
        Dim Part As String
        Dim Parts() As String = Split("2sd4-7635-9g69-4556", "-")
        For Each Part In Parts
            MsgBox(Part)
        Next

Also you might find the following functions usefull:
Visual Basic:
        System.IO.Path.Combine("C:\Dir", "File.txt") 
        System.IO.Path.GetExtension("C:\Dir\File.txt") 
        System.IO.Path.GetFileName("C:\Dir\File.txt") 
        Microsoft.VisualBasic.Right("asdfsdf", 3)
        Microsoft.VisualBasic.Left("asdfsdf", 3)
        Microsoft.VisualBasic.Mid("asdfsdf", 3, 2)
        Len("asdfsdf") 'Lenght of string
        Str(3) 'Value to string conversion
        Val("345") 'String to value conversion
 
You may want to consider using the Split() function built into the string class.
Visual Basic:
Dim Parts As String() = ("2sd4-7635-9g69-4556").Split("-"c)
For Each Part As String In Parts
    MessageBox.Show(Part)
Next
Using non-vb functions makes things easier for C# (or J# or C++, etc) users to understand your code, in the event that they need to look at it for some reason, and makes your code easier to translate if you ever need to. I have plenty of VB.NET code that I translate to C# when I need it, and having used common .Net functions makes life a little easier for me.
 
Marble, I've gotta agree with you on that point. Using common .NET methods instead of VB only makes converting alot easier, and not only will it help other programmers understand VB code; once you get used to programming that way in VB it makes it easier for the VB programmer to understand c#, j# etc.
 
It's also a good habit if you plan on expanding your computing skills into other .Net languages because it means less to learn later on.
 
Back
Top