Resolved return all letters left of number in string

Fedaykin

Active member
Joined
Mar 20, 2013
Messages
30
Programming Experience
Beginner
I'm trying to return only the first letters before the first number in as string. I tried several iterations of Regex and gave up on that.

I want to do something like:

VB.NET:
Dim source as String = "CP1,CP3-CP5,CP8"
Dim rc As String = Left(source, "[0-9]"))

[\CODE]

In this instance I just want to return "CP".
 
Last edited:
Test each character with Char.IsLetter

VB.NET:
 Dim str, newstr As String, ch As Char, N As Integer
        newstr = ""
        str = "CP1,CP3-CP5,CP8"
        N = str.Length
        For x As Integer = 0 To N - 1
            ch = str.Chars(x)
            If Char.IsLetter(ch) Then
                newstr &= ch
            Else
                Exit For
            End If
        Next
        MessageBox.Show(newstr)
 
Works perfectly, thank you!

I really thought there was a simple one-liner for this particular function, but your solution works great.
 
I really thought there was a simple one-liner for this particular function
There is:
Dim substr = New String(str.TakeWhile(Function (ch) Not Char.IsDigit(ch)).ToArray())
Any time you use a loop, there's most likely a way to collapse the code using a LINQ query. It's not always the best idea, because it can make the code hard to read. Not so much in this case though, I think.
 
Yes, in my search for this solution I read a few times about LINQ in place of loops. I'm going to pop this one in there too to see how it works. Thank you.
 
There is:
Dim substr = New String(str.TakeWhile(Function (ch) Not Char.IsDigit(ch)).ToArray())
Any time you use a loop, there's most likely a way to collapse the code using a LINQ query. It's not always the best idea, because it can make the code hard to read. Not so much in this case though, I think.
Note that that code will get all characters before the first digit. If you want all the leading letters then you should use this:
Dim substr = New String(str.TakeWhile(Function (ch) Char.IsLetter(ch)).ToArray())
The result will be the same for your example data but, if you had something that was neither a letter nor a digit in between then the results would differ.
 
Back
Top