Extract number from text

Hi

Given a number such as:

0824518765

How can I extract that best from some text in c#?

The number will always begin with 0, and is 10 digits long, but there may be spaces or hyphens between
zattzAsked:
Who is Participating?
 
käµfm³d 👽Commented:
A regex could be an option:

using System.Text.RegularExpressions;

...

Match m = Regex.Match(targetString, @"\b0(?:[ -]*\d){9}\b");

if (m.Success)
{
    string numericalValue = m.Groups[0].Value;
}

Open in new window

0
 
Meir RivkinFull stack Software EngineerCommented:
does it appear randomly?
can u post some text example?
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
you can replace individual characters (strings) and the parse the resulting string eg.

String s = "082 451-87 - 65";
UInt64 l = UInt64.Parse(s.Replace("-", "").Replace(" ", ""));

l is 824518765
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
zattzAuthor Commented:
The number changes dynamically. I am parsing it out of some text files. I presume a regex is needed.
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
ps.  Numerical values do NOT have leading zero's so  0824518765 is not a numerical value

If you wanted the string then using the above example
String s = "082 451-87 - 65";
s = s.Replace("-", "").Replace(" ", "");  //s is 0824518765
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
>>I presume a regex is needed.

No - see my code earlier.  A regex is an option, not a requirement.
0
 
käµfm³d 👽Commented:
@AndyAinscow

Your example is a tad on the trivial side, though. It does not demonstrate the "from some text" aspect of the OP. I'm certain it could be made to do so, but your example doesn't really convey this.
0
 
zattzAuthor Commented:
A regex is definitely needed because the number is a phone number, and it changes...
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
@kaufmed
Extract of question:   The number will always begin with 0, and is 10 digits long, but there may be spaces or hyphens between

My example fits the complete stated requirements - it copes with both hyphens and spaces.
0
 
zattzAuthor Commented:
Thanks so much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.