Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the first number in a string using .NET 3.5

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.

like image 260
nailitdown Avatar asked Dec 10 '09 08:12

nailitdown


3 Answers

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');
like image 60
David Hedlund Avatar answered Nov 15 '22 05:11

David Hedlund


Try something like this

string s = "XX0234X";
Regex rg = new Regex("\\d+");
Match m = rg.Match(s);
like image 44
Adriaan Stander Avatar answered Nov 15 '22 05:11

Adriaan Stander


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);
            }
        }

    }
}
like image 42
Paolo Tedesco Avatar answered Nov 15 '22 05:11

Paolo Tedesco