How to write Regex for numbers only in C#?

CsharpServer Side ProgrammingProgramming

A regular expression is a pattern that could be matched against an input text.

The .Net framework provides a regular expression engine that allows such matching.

A pattern consists of one or more character literals, operators, or constructs.

Here are basic pattern metacharacters used by RegEx −

* = zero or more
? = zero or one
^ = not
[] = range

The ^ symbol is used to specify not condition.

the [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z

Example

class Program{
   public static void Main(){
      string num = "123dh";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

Output

False

Example

class Program{
   public static void Main(){
      string num = "123";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

Output

True

Example

class Program{
   public static void Main(){
      string num = "123.67";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}

Output

True
raja
Published on 25-Sep-2020 11:16:45
Advertisements