How to Check if there is any Alphabet or Non Alphanumeric Character in a String

Sometimes in our Project we may need to check if a particular string can be converted to a number or not. 

In practical world any string can be converted as Number if it contains only number Or essentially it should not contain any non alphanumeric character or alphabet. 

In my project, I faced a problem while creating search and Match engine, I needed to match a string with Salary column when it is eligible for getting converted to a number. I had seen many approaches on internet but then decided to write my own to make it very easy. 

I have written the following C# code with the help of Regex class to achieve the same.

#region Check If there is no  Alphabet and no non-Alphanumeric //character 

public bool CheckIfAlphabet(string salDesc)

{

            Regex objAlphaPattern = new Regex(@"^\d+$"); 

            return objAlphaPattern.IsMatch(salDesc);

}
#endregion

 

Explanation 

Above method accepts a string as a parameter. 

If there is any Alphabet or  non-Alphanumeric character above method will Return False. 

If there is no  Alphabet and no non-Alphanumeric character Then it will return  true. 

Example :-

1. Input :- 908765 

Output :- True

2. Input :- ab08765 

Output :- False 

3. Input :- ab08+65 

Output :- False

4. Input :- 908#65  

Output :- False 

Remember that for using above code you need to add System.Text.RegularExpressions as Referance to your project. 

Though a very small code but yet very powerful. 

Hope it atleast helps someone. 

Thanks Prasoon.


Similar Articles