In this code snippet, we will see how to identify if a string is numeric or not in C#. This code snippet helps for the fresh or experienced C# developers.
Using Regular Expression:
Example 1: Give input is numeric
using System;
using System.Text.RegularExpressions;
namespace SampleApp
{
class FindNumeric
{
public static void Main()
{
var regex = new Regex(@"^\d+$");
var str = "1000";
if (regex.IsMatch(str))
{
Console.WriteLine("This is a numeric value");
}
else
{
Console.WriteLine("This is not a numeric value");
}
Console.ReadKey();
}
}
}
Output:
This is a numeric value
Example 2: Give input is non-numeric
using System;
using System.Text.RegularExpressions;
namespace SampleApp
{
class FindNumeric
{
public static void Main()
{
var regex = new Regex(@"^\d+$");
var str = "TechieClues";
if (regex.IsMatch(str))
{
Console.WriteLine("This is a numeric value");
}
else
{
Console.WriteLine("This is not a numeric value");
}
Console.ReadKey();
}
}
}
Output:
This is not a numeric value
Using Enumerable.All Method
Example:
using System;
using System.Linq;
namespace SampleApp
{
class FindNumeric
{
public static void Main()
{
var str = "1000";
if (str.All(char.IsDigit))
{
Console.WriteLine("This is a numeric value");
}
else
{
Console.WriteLine("This is a not a numeric value");
}
var str1 = "TechieClues";
if (str1.All(char.IsDigit))
{
Console.WriteLine("This is a numeric value");
}
else
{
Console.WriteLine("This is not a numeric value");
}
Console.ReadKey();
}
}
}
Output:
This is a numeric value
This is not a numeric value
Comments (0)