• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#用正则表达式判断字符串是否为纯数字

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Regex regex = new System.Text.RegularExpressions.Regex("^(-?[0-9]*[.]*[0-9]{0,3})$");

string itemValue="abc123"

bool b=regex.IsMatch(itemValue); 

if(b==true)

{

  //是纯数字

}

else

{

  //不是纯数字

}

下面这段代码是判断是否为纯数字,如果是就加1,如果是以字母开头的数字字符串,字母不变,后面数字加1

 

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             string str = Console.ReadLine();
 6             string strTmp = "";
 7             if (IsNumeric(str))
 8             {
 9                 strTmp = (ConvertToLong(Convert.ToInt32(str) + 1).ToString().PadLeft(str.Length, \'0\'));
10             }
11             else
12             {
13                 int iNum = str.Length;
14                 int j = 0;
15                 for (int i = 0; i < iNum; i++)
16                 {
17                     if (!IsNumeric(str[i].ToString()))
18                     {
19                         j++;
20                     }
21                 }
22                 strTmp = str.Substring(0, j) + (ConvertToLong(Convert.ToInt32(str.Substring(j, str.Length - j)) + 1).ToString().PadLeft(str.Substring(j, str.Length - j).Length, \'0\'));
23             }
24             Console.WriteLine(strTmp);
25             Console.ReadKey();
26         }
27         public static bool IsNumeric(string itemValue)
28         {
29             return (IsRegEx("^(-?[0-9]*[.]*[0-9]{0,3})$", itemValue));
30         }
31         public static long ConvertToLong(object value)
32         {
33             if (value == null || value.ToString().Trim() == "")
34             {
35                 return 0;
36             }
37 
38             long nValue;
39             long.TryParse(value.ToString(), out nValue);
40             
41             return nValue;
42         }
43         public static bool IsRegEx(string regExValue, string itemValue)
44         {
45             try
46             {
47                 Regex regex = new System.Text.RegularExpressions.Regex(regExValue);
48                 if (regex.IsMatch(itemValue)) return true;
49                 else return false;
50             }
51             catch (Exception)
52             {
53                 return false;
54             }
55             finally
56             {
57             }
58         }
59     }
View Code

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#生成缩略图发布时间:2022-07-13
下一篇:
【《Effective C#》提炼总结】提高Unity中C#代码质量的21条准则发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap