Check String for Number of Numeric Characters

Posted: April 26, 2011 in ASP.Net

If you need to know the number of numeric characters in a string, you can try the following:
VB.NET

Dim strValue as String = '"a1b2c3d4e5'"
Dim rexNonNumeric As New System.Text.RegularExpressions.Regex("[^0-9]")
Dim strNumeric As String = rexNonNumeric.Replace(strValue, String.Empty)

If strNumeric.Length = 5 Then
  ' Do something here...
End If

C#

string strValue = "a1b2c3d4e5";
System.Text.RegularExpressions.Regex rexNonNumeric = new System.Text.RegularExpressions.Regex("[^0-9]");
string strNumeric = rexNonNumeric.Replace(strValue, string.Empty);

if (strNumeric.Length = 5) 
{
  // Do something here...
}

Now to only check for non numeric characters in a string, you would replace the reqular expression as follows:
VB.NET

Dim rexNumeric As New System.Text.RegularExpressions.Regex("[0-9]")

C#

System.Text.RegularExpressions.Regex rexNumeric = new System.Text.RegularExpressions.Regex("[0-9]");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s