Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get all digits from a string [duplicate]

Is there any better way to get take a string such as "(123) 455-2344" and get "1234552344" from it than doing this:

var matches = Regex.Matches(input, @"[0-9]+", RegexOptions.Compiled);  return String.Join(string.Empty, matches.Cast<Match>()                                 .Select(x => x.Value).ToArray()); 

Perhaps a regex pattern that can do it in a single match? I couldn't seem to create one to achieve that though.

like image 876
Chris Marisic Avatar asked Apr 14 '10 03:04

Chris Marisic


People also ask

How do you find all the numbers in a string Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do I extract digits from a string?

The following example shows how you can use the replaceAll() method to extract all digits from a string in Java: // string contains numbers String str = "The price of the book is $49"; // extract digits only from strings String numberOnly = str. replaceAll("[^0-9]", ""); // print the digitts System. out.


2 Answers

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray()); 
like image 76
Matt Hamilton Avatar answered Sep 23 '22 02:09

Matt Hamilton


Have you got something against Replace?

return Regex.Replace(input, @"[^0-9]+", ""); 
like image 44
Alan Moore Avatar answered Sep 21 '22 02:09

Alan Moore