Get number from string with compiled Regular exceptions in CSharp

Description

The following code shows how to get number from string with compiled Regular exceptions.

Example


//from www  . j av a2s.  co m
using System;
using System.Data;
using System.Text.RegularExpressions;

class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(GetNumberFromStrFaster(IsNum));    // +111
      Console.WriteLine(GetNumberFromStrFaster(IsNotNum));  // 
      Console.WriteLine(GetNumberFromStrFaster(IsFloat));    // 23.11
      Console.WriteLine(GetNumberFromStrFaster(IsExp));    // 
        }
    public static string GetNumberFromStrFaster(string str)
    {
      str = str.Trim();
      Match m = new Regex(@"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$", RegexOptions.Compiled).Match(str);
      return (m.Value);
    }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var