The c# regex.match method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation.Below is a string extension method that uses c# regex matches to check if the string is alphanumeric.It will return true if given string contain only number and alphabets.
using System;
using
System.Collections.Generic;
using
System.Text;
using
System.Text.RegularExpressions;
public static class CheckString
{
public static bool
IsAlphanumeric(string source)
{
Regex
pattern = new Regex("[^0-9a-zA-Z]");
return
!pattern.IsMatch(source);
}
}
// THE Below
Example USe Code.
class Program
{
static void Main(string[]
args)
{
string
testString = Console.ReadLine();
if
(CheckString.IsAlphanumeric(testString))
Console.WriteLine("Yes string is Alphanumeric!");
else
Console.WriteLine("No string is not Alphanumeric!");
Console.ReadKey();
}
}
some time we require Only numbers can be enter by user into a Textbox for that We can use Regular expression validator in asp.net for this:
In the validation expression property keep ^\d+$.
Example:
In the validation expression property keep ^\d+$.
Example:
<asp:TextBox ID="txtnumber"
runat="server"
ValidationGroup="number"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
ControlToValidate="txtnumber"
ErrorMessage="Please Enter Only
Numbers" ValidationExpression="^\d+$" ValidationGroup="number"></asp:RegularExpressionValidator>