How to get the last numeric digits in a string

  • Thread starter Thread starter Appr3nt1c3
  • Start date Start date
A

Appr3nt1c3

Hello everyone,

How can I get the last numeric digits of a string? The string may
contain non-numeric characters but I only want to obtain the last part
that contains numbers.

Example:

Input: "0001"
Output: "0001"

Input: "001-0001"
Output: "0001"

Input: "001-A001"
Output: "001"

Input: "001-001A"
Output: "" or "0"

Input: "001-0001-1"
Output: "1"

I know than this can be done using by iterating each character in the
string and making if..else conditions for each character, but is there
a one-liner that can do this?

BTW, the output's length is not fixed.

Thanks,

Diego
 
Appr3nt1c3 said:
Hello everyone,

How can I get the last numeric digits of a string? The string may
contain non-numeric characters but I only want to obtain the last part
that contains numbers.
Input: "001-001A"
Output: "" or "0"

How does this match to your definition? Should it be "001"?
I know than this can be done using by iterating each character in the
string and making if..else conditions for each character, but is there
a one-liner that can do this?

This is not just one line, but here is my suggestion:

Dim Input As String = "001-001A"
Dim Parts As String() = Input.Split("-")
Dim Result As String = ""
For i As Integer = Parts.Length - 1 To 0 Step -1
If IsNumeric(Parts(i)) Then
Result = Parts(i)
Exit For
End If
Next

I'm sure that somebody will post a nice LINQ-command to make this with one
line. :-)

-Teemu
 
How does this match to your definition? Should it be "001"?


This is not just one line, but here is my suggestion:

        Dim Input As String = "001-001A"
        Dim Parts As String() = Input.Split("-")
        Dim Result As String = ""
        For i As Integer = Parts.Length - 1 To 0 Step -1
            If IsNumeric(Parts(i)) Then
                Result = Parts(i)
                Exit For
            End If
        Next

I'm sure that somebody will post a nice LINQ-command to make this with one
line. :-)

 -Teemu

Hi Teemu,

Thank you for your reply.
How does this match to your definition? Should it be "001"?

Sorry for the confusing post. The output can be "". I can just return
"0" from my calling function if the result is "".

BTW, I'm using VB .Net 2005, so I can't use LINQ.

Been reading up on RegEx but can't seem to get its concept yet.

Thanks,

Diego
 
Sorry for the confusing post. The output can be "". I can just return
"0" from my calling function if the result is "".

But if you want the last numeric part of this string "001-001A" I don't
understand why the result should be "" or "0" instead of "001"?

Did you try my code does it work or are you looking for more elegant
solution?

-Teemu
 
Back
Top