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 开发者_JS百科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.
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');
Try something like this
string s = "XX0234X";
Regex rg = new Regex("\\d+");
Match m = rg.Match(s);
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);
}
}
}
}
精彩评论