Finding the first number in a string using .NET 3.5

I have a bunch of lines from which I need to extract numbers. They are in the format:

XXXX001 XXXXXXX004 XX0234X 

There are many of them, and I need to sort through them all and extract all the numbers.

So, what is the fastest / most efficient way, using ASP.NET 3.5, to find the first instance of a number inside a string?

Update I should have included more information - getting answers giving me ideas on how to extract all numbers and not find the first index. Not a problem - I'm sure others will find them useful.

In my case, I really need an index, because I'm doing a bit more string analysis (i.e. there might be a range XXXX0234-0237XX or a couple XXXXX0234 & 0238XX.

Finding the index of the first number helps me orient the interesting part of the string to check.

+4
source share
3 answers

a lot of people will post a fancy regular solution to your problem, but I would prefer it, although it requires entering all numbers manually

 int ix = myString.IndexOfAny('1', '2', '3', '4', '5', '6', '7', '8', '9', '0'); 
+12
source

Try something like this

 string s = "XX0234X"; Regex rg = new Regex("\\d+"); Match m = rg.Match(s); 
+5
source

Edit: to also find the delimiter and second value at a time, you can use a regex like this.

 using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string[] strings = new string[] { "XXXX001&042", "XXXXXXX004-010XXX", "XX0234X" }; Regex regex = new Regex(@"(?<first>\d+)((?<separator>[-&])(?<second>\d+))?"); foreach (string s in strings){ Match match = regex.Match(s); Console.WriteLine("First value: {0}",match.Groups["first"].Value); if (match.Groups["separator"].Success) { Console.WriteLine("Separator: {0}", match.Groups["separator"].Value); Console.WriteLine("Second value: {0}", match.Groups["second"].Value); } } } } 
+2
source

All Articles