Difference between revisions of "Extract numbers from an alpha numeric string"

From CodeCodex

m (Reverted edit of 61.89.28.28, changed back to last version by Nostromo)
Line 6: Line 6:
 
   Dim i As Long, k As Long, j As Long
 
   Dim i As Long, k As Long, j As Long
 
   For i = 0 To Len(Str)
 
   For i = 0 To Len(Str)
     k = Mid(Str, i + 1, 1)
+
     k = Mid(Str, i   1, 1)
 
     If Not k >= 0 Or k <= 9 Then
 
     If Not k >= 0 Or k <= 9 Then
       j = j + k
+
       j = j   k
 
     End If
 
     End If
 
   Next
 
   Next

Revision as of 21:31, 1 July 2007

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