C#用正则表达式判断字符串是否纯数字vs用Char.IsDigit 方法遍历字符数组是否纯数字

目录

一、使用的方法

1.正则表达式

2.Char.IsDigit 方法

二、源码

1.源代码

2.生成效果


一、使用的方法

1.正则表达式

        在程序运行过程中,经常需要用户输入数字信息,如输入员工年龄、工资等。使用正则表达式Regex类的IsMatch方法,可以有效地判断用户输入的信息是否为数字。

        用于判断字符串是否纯数字的正则表达式可以是:^[0-9]*$,其中,[0-9]*表示匹配零个至多个数字,“*”限定符用于限定指定的字符至少出现0次。实现相同目的的正则表达式还可以是:^\d*$、^\d+$。

2.Char.IsDigit 方法

        先用ToCharArray()静态方法把输入的字符串转成字符数组,再对数组遍历并用Char.IsDigit()方法判断数组中是否包含非数字,一旦包含非数字就显示输入的字符不是纯数字。

        下面分享源码: 

二、源码

1.源代码

// 用正则表达式验证是否纯数字
// 用Char.IsDigit 方法遍历字符串是否纯数字
namespace _078
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private TextBox? textBox1;
        private Button? button1;
        private Label? label1;
        private Button? button2;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(146, 17),
                Name = "textBox1",
                Size = new Size(100, 23),
                TabIndex = 2
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(171, 44),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 1,
                Text = "验证1",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(35, 23),
                Name = "label1",
                Size = new Size(80, 17),
                TabIndex = 0,
                Text = "输入字符串:"
            };
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(171, 71),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 3,
                Text = "验证2",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(280, 100),
                TabIndex = 0,
                TabStop = false,
                Text = "groupBox1"
            };
            groupBox1.Controls.Add(button2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(304, 123);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "正则表达式判断输入是否纯数字";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (!(textBox1!.Text == ""))
            {
                if (!IsNumber(textBox1!.Text.Trim()))
                {
                    MessageBox.Show("输入的字符不是纯数字", "验证1");
                }
                else
                {
                    MessageBox.Show("输入的字符是纯数字", "验证1");
                }
            }
            else
            {
                MessageBox.Show("输入的字符不能为空", "验证1");
            }
        }
        /// <summary>
        /// 先用ToCharArray()方法把输入的字符串转成字符数组
        /// 再对字符数组遍历,用Char.IsDigit()方法判断数组中是否包含非数字
        /// 一旦包含非数字就显示输入的字符不是纯数字
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {   
            if (!(textBox1!.Text == ""))
            {
                char[] charArr = textBox1!.Text.ToCharArray();
                foreach (char c in charArr)
                {
                    if (!Char.IsDigit(c))
                    {
                        MessageBox.Show("输入的字符不是纯数字", "验证2");
                        return;
                    }
                }
                MessageBox.Show("输入的字符是纯数字", "验证2");
            }
            else
            {
                MessageBox.Show("输入的字符不能为空", "验证2");
            }
        }

        /// <summary>
        /// 验证输入是否为数字
        /// 等效的正则^\d*$、^\d+$
        /// </summary>
        /// <param name="number">用户输入的字符串</param>
        /// <returns>方法返回布尔值</returns>
        public static bool IsNumber(string number)
        {
            return MyRegex().IsMatch(number);
        }

        //[System.Text.RegularExpressions.GeneratedRegex(@"^[0-9]*$")]
        [System.Text.RegularExpressions.GeneratedRegex(@"^\d+$")]
        private static partial System.Text.RegularExpressions.Regex MyRegex();
    }
}

2.生成效果

 

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 08:16:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 08:16:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 08:16:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 08:16:01       20 阅读

热门阅读

  1. 物流无人机在哪些场景最适合应用?

    2024-02-01 08:16:01       29 阅读
  2. Flink 集成和使用 Hive Metastore

    2024-02-01 08:16:01       37 阅读
  3. C++ 结构体的构造函数

    2024-02-01 08:16:01       33 阅读
  4. 面阵相机拍摄运动的物体怎样保证图像清晰

    2024-02-01 08:16:01       41 阅读
  5. TensorFlow2实战-系列教程14:Resnet实战2

    2024-02-01 08:16:01       44 阅读
  6. 3D Gaussian Splatting-实时辐射场渲染技术

    2024-02-01 08:16:01       34 阅读
  7. TensorFlow2实战-系列教程15:Resnet实战3

    2024-02-01 08:16:01       39 阅读
  8. CSS 中的 :is(), :where(), 和 :has() 选择器简介

    2024-02-01 08:16:01       33 阅读
  9. 使用certbot申请https通配符证书【阿里云篇】

    2024-02-01 08:16:01       38 阅读
  10. K8S网络

    K8S网络

    2024-02-01 08:16:01      33 阅读
  11. k8s学习-数据管理

    2024-02-01 08:16:01       29 阅读
  12. brpc之单例

    2024-02-01 08:16:01       33 阅读