• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 524
  • Last Modified:

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
0
zattz
Asked:
zattz
  • 4
  • 3
  • 2
  • +1
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
does it appear randomly?
can u post some text example?
0
 
AndyAinscowCommented:
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
 
zattzAuthor Commented:
The number changes dynamically. I am parsing it out of some text files. I presume a regex is needed.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
AndyAinscowCommented:
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
 
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
 
AndyAinscowCommented:
>>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
 
AndyAinscowCommented:
@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

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 4
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now