C # determine whether a string is a number

Source: Internet
Author: User

1. Regular Expression
A.

Using System;
Using System. Text. RegularExpressions;

Public bool IsNumber (String strNumber)
{
Regex objNotNumberPattern = new Regex ("[^ 0-9.-]");
Regex objTwoDotPattern = new Regex ("[0-9] * [.] [0-9] * [.] [0-9] *");
Regex objTwoMinusPattern = new Regex ("[0-9] * [-] [0-9] * [-] [0-9] *");
String strValidRealPattern = "^ ([-] | [.] | [-.] | [0-9]) [0-9] * [.] * [0-9] + $ ";
String strValidIntegerPattern = "^ ([-] | [0-9]) [0-9] * $ ";
Regex objNumberPattern = new Regex ("(" + strValidRealPattern + ") | (" + strValidIntegerPattern + ")");

Return! ObjNotNumberPattern. IsMatch (strNumber )&&
! ObjTwoDotPattern. IsMatch (strNumber )&&
! ObjTwoMinusPattern. IsMatch (strNumber )&&
ObjNumberPattern. IsMatch (strNumber );
}

B.

Public static bool IsNumeric (string value)
{
Return Regex. IsMatch (value, @ "^ [+-]? D * [.]? D * $ ");
}
Public static bool IsInt (string value)
{
Return Regex. IsMatch (value, @ "^ [+-]? D * $ ");
}
Public static bool IsUnsign (string value)
{
Return Regex. IsMatch (value, @ "^ d * [.]? D * $ ");
}

2. Traverse

Public bool isnumeric (string str)
{
Char [] ch = new char [str. Length];
Ch = str. ToCharArray ();
For (int I = 0; I <ch. Length; I ++)
{
If (ch [I] <48 |

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.