How to extract numbers from a string using C#
Here's two common ways of extracting 1st, last and all numbers from string of mixed characters in C# using Linq & Regular Expressions. Elapsed times are also provided.Source code
using System; using System.Linq; using System.Text.RegularExpressions; using System.Diagnostics; public class Program { public static void Main() { Console.WriteLine("Parsing string '123as456'\n"); Stopwatch sw = new Stopwatch(); sw.Start(); //regex get all numbers Console.WriteLine(string.Format("{0:00} regex split all numbers", string.Join(null,Regex.Split("123as456", "[^\\d]")))); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //regex get all numbers Console.WriteLine(string.Format("{0:00} regex replace all numbers", Regex.Replace("123as456", @"\D",""))); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //regex get 1st numbers Console.WriteLine(string.Format("{0:00} regex match 1st number", Regex.Match("123as456", @"^\d+").ToString())); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //regex get last number Console.WriteLine(string.Format("{0:00} regex match last number ", Regex.Match("123as456", @"\d+$").ToString())); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); Console.WriteLine("Parsing string '222star10bucks'\n"); //linq all numbers in a string successively Console.WriteLine( string.Format("{0:00} linq select all numbers where long format", new string( (from t in "222star10bucks" where char.IsDigit(t) select t).ToArray() ) ) ); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //linq all numbers in a string successively Console.WriteLine(string.Format("{0:00} linq where digits all numbers", new String("222star10bucks".Where(Char.IsDigit).ToArray()))); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //linq 1st number in a string Console.WriteLine(string.Format("{0:00} linq takewhile 1st number", new String("222star10bucks".TakeWhile(Char.IsDigit).ToArray()))); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); sw.Restart(); //linq last number in a string, must end in a number Console.WriteLine(string.Format("{0:00} linq reverse takewhile last number", string.Concat("222star10".ToArray().Reverse().TakeWhile(char.IsNumber).Reverse()))); sw.Stop(); Console.WriteLine(string.Format(" ﹂ in {0} ticks",sw.ElapsedTicks.ToString("N0"))); } }
No comments:
Post a Comment