Remove non-numbers from a string

From CodeCodex

Related content:

Implementations[edit]

C[edit]

if buff's content is: "hello 2 wor145+ld--1! how 19521 a*re 1254y**ou?" then the content of buff_02 will be: "21451195211254"

#include <string.h>

while (i != strlen (buff))
{
	if ((buff[i] >= 48) && (buff[i] <= 57))
	{
		buff_02[j] = buff[i];
		i++;
		j++;
	}
	else
	{
		i++;
	}
}

D[edit]

Prints: 19254

import std.stdio, std.string;

void main() {
    writefln("how19 a*re 254y**ou?".removechars("^0-9"));
}

Erlang[edit]

S = "how19 a*re 254y**ou?".
re:replace(S, "[^0-9]", "", [global, {return, list}]).

Haskell[edit]

removeNonNumbers :: String -> String
removeNonNumbers = filter Char.isDigit

Java[edit]

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("\\D","");
}

JavaScript[edit]

var s = "how19 a*re 254y**ou?";

document.write(s.replace(/\D/g, ""));

OCaml[edit]

# 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[edit]

s{\D}{}g; # remove all non-digits

PHP[edit]

Prints: 5678

$string = '5a6b7c8d';
$number = preg_replace('/\D/', '', $string);
echo $number;

Python[edit]

import re
s = "how19 a*re 254y**ou?"

# Using regular expressions
print re.sub("\D", "", s)

or

print ''.join(c for c in s if c.isdigit())

Ruby[edit]

Prints: 19254

s = "how19 a*re 254y**ou?"
print s.gsub(/\D/, "")

Visual Basic[edit]

Public Function ReturnNumbersOnly(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

Alternative function syntax for VB.NET 2005:
    Public Function ReturnNumbersOnly(ByVal sString As String) As String
        Dim retVal As String
        retVal = String.Empty
        For i As Int32 = 0 To sString.Length - 1
            If sString.Substring(i, 1) Like "[0-9]" Then
                retVal = retVal + sString.Substring(i, 1)
            End If
        Next i
        Return retVal
    End Function