Extract numbers from an alpha numeric string

From CodeCodex

Revision as of 21:31, 1 July 2007 by 62.231.243.136 (Talk)

Related content:

Implementations

Visual Basic

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

Perl, sed and others

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

Perl:

$example_string = "31415code9265codex358";
$example_string =~ s/[^0-9]//g;

sed:

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

Both result in: 314159265358

Tcl

proc extract_numbers s {regsub -all {[^0-9]} $s ""}
extract_numbers "31415code9265codex358"  ;# -> 314159265358