Extract numbers from an alpha numeric string

From CodeCodex

Related content:

Implementations[edit]

D[edit]

 string example = "31415code9265codex358";
 writefln( example.removechars("^0-9") );

Perl[edit]

This should also work for any language that supports Perl regex.

 $example_string = "31415code9265codex358";
 $example_string =~ s/\D//g;

result in: 314159265358

sed[edit]

echo "31415code9265codex358" | sed -e 's/[^0-9]//g'

result in: 314159265358

Tcl[edit]

 proc extract_numbers s {regsub -all {[^0-9]} $s ""}

 extract_numbers "31415code9265codex358"  ;# -> 314159265358

Visual Basic[edit]

Function OnlyNumbers(ByVal Str As String) As Long
  Dim i As Long, k As Long, j As Long
  For i = 0 To Len(Str)
    k = Mid(Str, i + 1, 1)
    If Not k >= 0 Or k <= 9 Then
      j = j + k
    End If
  Next
  OnlyNumbers= j
End Function

Or if you wanted to return the string with only numbers (MJS - 08/10/07):

Public Function ReturnNonAlpha(ByVar sString As String) As String
Dim i As Integer
For i = 1 To Len(sString)
    If Mid(sString, i, 1) Like "[0-9]" Then
        ReturnNonAlpha = ReturnNonAlpha + Mid(sString, i, 1)
    End If
Next i
End Function

Here's another function:

nStr = "31415code9265codex358"
For X = 1 To Len(nStr)
    If IsNumeric(Mid(nStr, X, 1)) = True Then
        nNum = nNum & Mid(nStr, X, 1)
    End If
Next X
MsgBox nNum

Zsh[edit]

example_string=a1b2c3
numeric_string_only=${example_string//[^0-9]/}