Use regular expression to get number from string in CSharp

Description

The following code shows how to use regular expression to get number from string.

Example


using System;//from   w  w w.j a v  a2  s.  co  m
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(GetNumberFromStr(IsNum));    // +111
      Console.WriteLine(GetNumberFromStr(IsNotNum));  // 
      Console.WriteLine(GetNumberFromStr(IsFloat));  // 23.11
      Console.WriteLine(GetNumberFromStr(IsExp));    // 
        }
    public static string GetNumberFromStr(string str)
    {
      str = str.Trim();
      Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
      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