Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return only Digits 0-9 from a String

I need a regular expression that I can use in VBScript and .NET that will return only the numbers that are found in a string.

For Example any of the following "strings" should return only 1231231234

  • 123 123 1234
  • (123) 123-1234
  • 123-123-1234
  • (123)123-1234
  • 123.123.1234
  • 123 123 1234
  • 1 2 3 1 2 3 1 2 3 4

This will be used in an email parser to find telephone numbers that customers may provide in the email and do a database search.

I may have missed a similar regex but I did search on regexlib.com.

[EDIT] - Added code generated by RegexBuddy after setting up musicfreak's answer

VBScript Code

Dim myRegExp, ResultString Set myRegExp = New RegExp myRegExp.Global = True myRegExp.Pattern = "[^\d]" ResultString = myRegExp.Replace(SubjectString, "") 

VB.NET

Dim ResultString As String Try       Dim RegexObj As New Regex("[^\d]")       ResultString = RegexObj.Replace(SubjectString, "") Catch ex As ArgumentException       'Syntax error in the regular expression End Try 

C#

string resultString = null; try {     Regex regexObj = new Regex(@"[^\d]");     resultString = regexObj.Replace(subjectString, ""); } catch (ArgumentException ex) {     // Syntax error in the regular expression } 
like image 820
Brian Boatright Avatar asked May 10 '09 00:05

Brian Boatright


People also ask

How do you extract only digits from a string in Python?

Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.

What is the regex for only numbers?

To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.


1 Answers

In .NET, you could extract just the digits from the string. Like this:

string justNumbers = new String(text.Where(Char.IsDigit).ToArray()); 
like image 68
Matt Hamilton Avatar answered Sep 27 '22 20:09

Matt Hamilton