Remove non-numbers from a string

From CodeCodex

Revision as of 23:42, 8 October 2007 by Tanktop (Talk | contribs)

Related content:

Implementations

Java

This code removes common symbols and numbers from a string, returning letters only. (Note, not all symbols are included.)

static String numbersOnly(String s) {
   return s.replaceAll("[A-Z]|[a-z]|[ !@#\\$%\\^&\\*\\(\\)_\\+\\-={}\\|:\"<>\\?\\-=\\[\\];',\\./`~'£€¥]","");
}

OCaml

# let remove_nondigit = Str.global_replace (Str.regexp "[^0-9]+") "";;
val remove_nondigit : string -> string = <fun>

For example:

# remove_nondigit "133t H4x0r";;
- : string = "13340"

Perl

<HIGHLIGHTSYNTAX language="perl"> s{[\D]}{}g; # remove all non-digits </HIGHLIGHTSYNTAX>

Visual Basic

Public Function ReturnNumbersOnly(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
        ReturnNumbersOnly = ReturnNumbersOnly + Mid(sString, i, 1)
    End If
Next i
End Function