sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

原文连接:https://blog.csdn.net/hedonister/article/details/292673?utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.baidujs&dist_request_id=1328741.40131.16170169543445497&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.baidujs

判断一个string是否可以为数字

方案一:Try...Catch(执行效率不高)
/// <summary>
/// 名称:IsNumberic
/// 功能:判断输入的是否是数字
/// 参数:string oText:源文本
/// 返回值: bool true:是 false:否
/// </summary>
/// <param name="oText"></param>
/// <returns></returns>
private bool IsNumberic(string oText)
{
try
         {
int var1=Convert.ToInt32 (oText);
return true;
         }
catch
{
return false;
}
}

方案二:正则表达式(推荐)
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*$");
}
方案三:遍历
a)
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 || ch[i]>57)
            return false;
    }
    return true;
}

b)
public bool IsInteger(string strIn) {
bool bolResult=true;
if(strIn=="") {
bolResult=false;
}
else {
foreach(char Char in strIn) {
if(char.IsNumber(Char))
continue;
else {
bolResult=false;
break;
}
}
}
return bolResult;
}

c)
public static bool isNumeric(string inString)
{
inString=inString.Trim();
bool haveNumber=false;
bool haveDot=false;
for(int i=0;i<inString.Length;i++)
{
if (Char.IsNumber(inString[i]))
{
haveNumber=true;
}
else if(inString[i]=='.')
{
if (haveDot)
{
return false;
}
else
{
haveDot=true;
}
}
else if(i==0)
{
if(inString[i]!='+'&&inString[i]!='-')
{
return false;
}
}
else
{
return false;
}
if(i>20)
{
return false;
}
}
return haveNumber;
}
}

方案四:改写vb的IsNumeric源代码(执行效率不高)

//主调函数
public static bool IsNumeric(object Expression)
{
      bool flag1;
      IConvertible convertible1 = null;
      if (Expression is IConvertible)
      {
            convertible1 = (IConvertible) Expression;
      }
      if (convertible1 == null)
      {
            if (Expression is char[])
            {
                  Expression = new string((char[]) Expression);
            }
            else
            {
                  return false;
            }
      }
      TypeCode code1 = convertible1.GetTypeCode();
      if ((code1 != TypeCode.String) && (code1 != TypeCode.Char))
      {
            return Utils.IsNumericTypeCode(code1);
      }
      string text1 = convertible1.ToString(null);
      try
      {
            long num2;
            if (!StringType.IsHexOrOctValue(text1, ref num2))
            {
                  double num1;
                  return DoubleType.TryParse(text1, ref num1);
            }
            flag1 = true;
      }
      catch (Exception)
      {
            flag1 = false;
      }
      return flag1;
}

//子函数
// return Utils.IsNumericTypeCode(code1);
internal static bool IsNumericTypeCode(TypeCode TypCode)
{
      switch (TypCode)
      {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Single:
            case TypeCode.Double:
            case TypeCode.Decimal:
            {
                  return true;
            }
            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            {
                  break;
            }
      }
      return false;
}
 

//-----------------
//StringType.IsHexOrOctValue(text1, ref num2))
internal static bool IsHexOrOctValue(string Value, ref long i64Value)
{
      int num1;
      int num2 = Value.Length;
      while (num1 < num2)
      {
            char ch1 = Value[num1];
            if (ch1 == '&')
            {
                  ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture);
                  string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2));
                  if (ch1 == 'h')
                  {
                        i64Value = Convert.ToInt64(text1, 0x10);
                  }
                  else if (ch1 == 'o')
                  {
                        i64Value = Convert.ToInt64(text1, 8);
                  }
                  else
                  {
                        throw new FormatException();
                  }
                  return true;
            }
            if ((ch1 != ' ') && (ch1 != '/u3000'))
            {
                  return false;
            }
            num1++;
      }
      return false;
}
//----------------------------------------------------
// DoubleType.TryParse(text1, ref num1);
internal static bool TryParse(string Value, ref double Result)
{
      bool flag1;
      CultureInfo info1 = Utils.GetCultureInfo();
      NumberFormatInfo info3 = info1.NumberFormat;
      NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3);
      Value = StringType.ToHalfwidthNumbers(Value, info1);
      if (info3 == info2)
      {
            return double.TryParse(Value, NumberStyles.Any, info2, out Result);
      }
      try
      {
            Result = double.Parse(Value, NumberStyles.Any, info2);
            flag1 = true;
      }
      catch (FormatException)
      {
            flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result);
      }
      catch (Exception)
      {
            flag1 = false;
      }
      return flag1;
}

方案五: 直接引用vb运行库(执行效率不高)

方法: 首先需要添加Visualbasic.runtime的引用
 代码中Using Microsoft.visualbasic;
 程序中用Information.isnumeric("ddddd");

 

-----------------------------------------------------------------通过正则表达式来判断补充-----------------------------
【方法二】:通过正则表达式来判断。
用正则表达式来验证字符串是否为数字字符串。我们要用到Regex类的isMatch()方法。该类在System.Text.RegularExpressions; 您可以通过using System.Text.RegularExpressions;导入命名空间来访问Regex类。也可以直接通过System.Text.RegularExpressions.Regex 来访问。
protected bool isNumberic(string message,out int result)
{
System.Text.RegularExpressions.Regex rex=
new System.Text.RegularExpressions.Regex(@"^\d+KaTeX parse error: Expected 'EOF', got '}' at position 185: … return false; }̲ 通过正则表达式判断是否匹配,…"))
{
//成功
Page.ClientScript.RegisterStartupScript(this.GetType(), “”, “”);
}
补充
//正则匹配
匹配中文字符的正则表达式: [\u4e00-\u9fa5]
匹配双字节字符(包括汉字在内):[^\x00-\xff]
匹配空行的正则表达式:\n[\s| ]\r
匹配HTML标记的正则表达式:/<(.)>.</\1>|<(.) />/
匹配首尾空格的正则表达式:(^\s)|(\s$)(像vbscript那样的trim函数)
匹配Email地址的正则表达式:\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*
匹配网址URL的正则表达式:http://([\w-]+.)+[\w-]+(/[\w- ./?%&=]*)?
以下是例子:
利用正则表达式限制网页表单里的文本框输入内容:
用正则表达式限制只能输入中文:οnkeyup=“value=value.replace(/[^\u4E00-\u9FA5]/g,’’)”
onbeforepaste=“clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\u4E00-\u9FA5]/g,’’))”
1.用正则表达式限制只能输入全角字符: οnkeyup=“value=value.replace(/[^\uFF00-\uFFFF]/g,’’)”
onbeforepaste=“clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\uFF00-\uFFFF]/g,’’))”
2.用正则表达式限制只能输入数字:οnkeyup="value=value.replace(/[^\d]/g,’’)
"onbeforepaste=“clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,’’))”
3.用正则表达式限制只能输入数字和英文:οnkeyup="value=value.replace(/[\W]/g,’’)
"onbeforepaste=“clipboardData.setData(‘text’,clipboardData.getData(‘text’).replace(/[^\d]/g,’’))”

---------------------------------------遍历字符串进行校验--------------------------------------------------------------------
https://jingyan.baidu.com/article/495ba8410eb14a38b30edec1.html

posted on 2021-03-29 19:28  sunny123456  阅读(507)  评论(0编辑  收藏  举报