Use regualr expression to check if a string is a number in CSharp

Description

The following code shows how to use regualr expression to check if a string is a number.

Example


    // w w  w.  j a  v a 2s.c  o 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(IsNumericRegEx(IsNum));    // True
      Console.WriteLine(IsNumericRegEx(IsNotNum));  // False
      Console.WriteLine(IsNumericRegEx(IsFloat));    // True
      Console.WriteLine(IsNumericRegEx(IsExp));    // False
        }
    public static bool IsNumericRegEx(string str)
    {
      str = str.Trim();
      return (Regex.IsMatch(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$"));
    }    
}

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