C#验证字符串是否包含汉字:用正则表达式 vs 用ASCII码 vs 用汉字的 Unicode 编码

目录

一、使用的方法

1.使用正则表达式验证字符串

2.使用正则表达式验证字符

3.用ASCII码判断

[4.用汉字的 Unicode 编码范围判断](#4.用汉字的 Unicode 编码范围判断)

二、实例

1.源码

2.生成效果


验证一个字符串是否是纯汉字或者包含有汉字的前提,是VS编辑器的默认编码格式设置为:选择 Unicode (UTF-8 带签名 - 代码页655001)。

一、使用的方法

1.使用正则表达式验证字符串

这种方法是有缺陷的(网上的很多例子都有这样的缺陷),是不完美的,是有限制的,换句话说,用正则表达式只能验证一个字符串是纯汉字的情况,当字符串是汉字、数字、字母、符号的无序混合体的时候,用正则表达式匹配字符串的返回值都是false,只有纯汉字的情况下返回值才是true。

cs 复制代码
// 用正则表达式验证字符串是否纯汉字
using System.Text.RegularExpressions;

namespace _088_1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);

            string[] input = ["ss","ss达到","到达","到达ss", "ss达到ss"];
            foreach(string inputItem in input)
            {
                if (ContainsChineseCharacter(inputItem))
                {
                    Console.WriteLine("字符串是纯汉字。");
                }
                else
                {
                    Console.WriteLine("无法判断是否包含汉字。");
                }
            }          
        }
        /// <summary>
        /// 使用正则表达式匹配纯汉字字符串
        /// </summary>
        static bool ContainsChineseCharacter(string input)
        {
            string pattern = @"^[\u4e00-\u9fa5]+$"; 
            return Regex.IsMatch(input, pattern);
        }
    }
}
//运行结果:
/*
无法判断是否包含汉字。
无法判断是否包含汉字。
字符串是纯汉字。
无法判断是否包含汉字。
无法判断是否包含汉字。

 */

2.使用正则表达式验证字符

当然了,不是说用正则表达式的方法解决不了这个问题,而是执行方法的细节用错了。

根据1里面的描述和例子,用正则表达式判断一个字符(char)是否是汉字100%的灵验。那么,标题的设计目的就解决了:先把字符串转换成字符数组,然后对数组遍历根据正则表达式判断当前字符是否汉字,只要有一个字符是汉字,那么就返回字符串中包含有汉字。

适用的正则表达式可以是:^\\u4E00-\\u9FA5+、\^\[\\u4E00-\\u9FA5\]\*、^\\u4e00-\\u9fa5{0,}、\^\[\\u4e00-\\u9fa5\]{1,} ,其中, ^\\u4e00-\\u9fa5{0,}$ 要做字符串为空的判断。

3.用ASCII码判断

在 ASCII码表中,英文的范围是0-127,而汉字则是大于127。因此,可以通过遍历判断一个字符串中是否包含有汉字。

4.用汉字的 Unicode 编码范围判断

汉字的 Unicode 编码范围是4e00-9fbb。因此,可以通过遍历判断一个字符串中是否包含有汉字。

好啦,翠花,上源码!

二、实例

本实例作者用3种方法实现设计目的:

验证1:用正则表达式验证字符串中是否包含汉字;

验证2:用ASCII码验证字符串中是否包含汉字;

验证3:用Unicode汉字编码验证字符串中是否包含汉字;

1.源码

cs 复制代码
// 用正则表达式验证字符串中是否包含汉字
// 用ASCII码验证字符串中是否包含汉字
// 用UNICODE汉字编码验证字符串中是否包含汉字
using System.Text.RegularExpressions;

namespace _088
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Label? label1;
        private Button? button1;
        private Button? button2;
        private Button? button3;
        private TextBox? textBox1;

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Load += Form1_Load;
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(6, 48),
                Name = "label1",
                Size = new Size(80, 17),
                TabIndex = 0,
                Text = "输入字符串:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(92, 42),
                Name = "textBox1",
                Size = new Size(100, 23),
                TabIndex = 1
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(199, 13),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 2,
                Text = "验证1",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(198, 42),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 3,
                Text = "验证2",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // button3
            // 
            button3 = new Button
            {
                Location = new Point(199, 71),
                Name = "button3",
                Size = new Size(75, 23),
                TabIndex = 4,
                Text = "验证3",
                UseVisualStyleBackColor = true
            };
            button3.Click += Button3_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(280, 100),
                TabIndex = 0,
                TabStop = false,
                Text = "验证是否含有汉字"
            };
            groupBox1.Controls.Add(button3);
            groupBox1.Controls.Add(button2);
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox1);
            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 = "验证字符串中是否含有汉字";
            UseWaitCursor = true;
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }
        /// <summary>
        /// 用正则表达式验证字符串中是否包含汉字
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            if(textBox1!.Text != "")
            {
                char[] input = textBox1!.Text.ToCharArray();
                foreach (char c in input)
                {
                    if (ContainsChineseCharacter(c.ToString()))
                    {
                        MessageBox.Show("字符串中含有汉字", "验证1");
                        return;
                    }
                    else { }
                }
                MessageBox.Show("字符串中没有汉字", "验证1");
            }
            else
            {
                MessageBox.Show("字符串不能为空", "验证1");
            }
        }
        /// <summary>
        /// 用ASCII码验证字符串中是否包含汉字
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {
            if (textBox1!.Text != "")
            {
                char[] input = textBox1!.Text.ToCharArray();
                foreach(char c in input)
                {
                    if (c > 127)
                    {
                        MessageBox.Show("字符串中含有汉字", "验证2");
                        return;
                    }
                    else { }
                }
                MessageBox.Show("字符串中没有汉字", "验证2");
            }
            else
            {
                MessageBox.Show("字符串不能为空", "验证2");
            }
        }
        /// <summary>
        /// 用UNICODE汉字编码验证字符串中是否包含汉字
        /// </summary>
        private void Button3_Click(object? sender, EventArgs e)
        {
            if (textBox1!.Text != "")
            {
                char[] input = textBox1!.Text.ToCharArray();
                foreach (char c in input)
                {
                    if (c >= 0x4e00 && c <= 0x9fbb)
                    {
                        MessageBox.Show("字符串中含有汉字", "验证3");
                        return;
                    }
                    else { }
                }
                MessageBox.Show("字符串中没有汉字", "验证3");
            }
            else
            {
                MessageBox.Show("字符串不能为空", "验证3");
            }
        }
        /// <summary>
        /// 使用正则表达式匹配纯汉字字符
        /// </summary>
        static bool ContainsChineseCharacter(string input)
        {
            string pattern = @"^[\u4e00-\u9fa5]+$";
            return Regex.IsMatch(input, pattern);
        }
    }
}

2.生成效果

相关推荐
吴声子夜歌6 小时前
正则指引——Ruby
开发语言·正则表达式·ruby
吴声子夜歌8 小时前
正则指引——Golang
开发语言·golang·正则表达式
吴声子夜歌1 天前
正则指引——PHP
开发语言·正则表达式·php
吴声子夜歌3 天前
正则指引——断言
正则表达式
吴声子夜歌3 天前
正则指引——匹配原理
java·正则表达式
吴声子夜歌4 天前
正则表达式——环视
开发语言·正则表达式
吴声子夜歌5 天前
正则表达式——边界
正则表达式
营养充电站5 天前
C++23 新特性在 CLion 中的实战体验
macos·docker·jupyter·正则表达式
吴声子夜歌6 天前
正则表达式——字符组
正则表达式