views:

157

answers:

3

I have a bunch of strings I need to extract numbers from. They're in the format:

XXXX001
XXXXXXX004
XX0234X

There's a lot of these, and i need to loop over them all and extract all the numbers.

So what's the quickest/most efficient way, using ASP.NET 3.5, to find the first instance of a number within a string?

Update I should've included more info - getting answers providing me with ideas on how to extract all the numbers, rather than find the first index. Not a problem - I'm sure others will find them useful.

In my case I actually need the index, because I'm doing some more analysis of the strings (ie. there may be a range XXXX0234-0237XX or a pair XXXXX0234&0238XX.

Finding the index of the first number helps me target the interesting part of the string for inspection.

+4  A: 

a lot of people would post a fancy regex solution to your problem, but i'd actually prefer this, eventhough it does require typing out all numbers manually

int ix = myString.IndexOfAny('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
David Hedlund
This finds the index of the first digit. In addition to this you need to find the next non-digit, then do a substring. Three lines instead of one line of very simple regex.
yu_sha
what? no, it's done, with that. *what's the quickest/most efficient way, using ASP.NET 3.5, to find the first instance of a number within a string?* That is the entire question. I think you misread the question with regards to the looping. They're actually different strings that are being iterated. No substring needed.
David Hedlund
Great answer. I was fooling around with linq and regex, when there was this much simpler solution.
nailitdown
+3  A: 

Try something like this

string s = "XX0234X";
Regex rg = new Regex("\\d+");
Match m = rg.Match(s);
astander
+2  A: 

Edit: to find also the separator and the second value in one go, you might 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);
            }
        }

    }
}
Paolo Tedesco
to get all the results use regex.matches and loop through them
Paul Creasey
+1 because this actually helped me with another problem.
nailitdown