Difference between revisions of "Remove non-numbers from a string"

From CodeCodex

(Perl)
(Implementations)
Line 17: Line 17:
 
s{[\D]}{}g; # remove all non-digits
 
s{[\D]}{}g; # remove all non-digits
 
</HIGHLIGHTSYNTAX>
 
</HIGHLIGHTSYNTAX>
 +
 +
===Visual Basic===
 +
<pre>
 +
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
 +
</pre>
  
  
Line 23: Line 35:
 
[[Category:Perl]]
 
[[Category:Perl]]
 
[[Category:String]]
 
[[Category:String]]
 +
[[Category:Visual Basic]]

Revision as of 23:42, 8 October 2007

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