检测中文

项目中有一个地方需要检测用户的输入,而且客户要求不能输入中文。限制只能输入中文的方法比较多,主要是以下的方法:

1、检测每个字符的Ascii ,判断是否在 255 以内;

2、用正则表达式。eg: [^/x00-/xff]

以下就是用 2 来实现的:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the data.");

            string strTest = Console.ReadLine();

            while(strTest != null)
            {
                if (strTest.Trim().ToLower().Equals("stop") )
                {
                    break;
                }

                IsChinese(strTest);

                Console.WriteLine("/nPlease enter the data.");
                strTest = Console.ReadLine();
            }
           
        }

        /// <summary>
        /// 检查是否为汉字
        /// </summary>
        /// <param name="str">需要检查的字符串 </param>
        /// <returns>true:字符串中有汉字 </returns>
        /// 实现流程:
        ///     1、构造正则匹配表达式
        ///     2、判断是否有中文
        private static bool IsChinese(string str)
        {
            string strChinesePatterns = "[^/x00-/xff]";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(strChinesePatterns);
            System.Text.RegularExpressions.MatchCollection mch = reg.Matches(str, 0);
            if (mch.Count > 0)
            {
                foreach(Match mach in mch)
                    Console.WriteLine(string.Format("{0} = {1} ", mach.Index.ToString(), mach.Value));

                Console.WriteLine(string.Format("[ {0} ] contains {1} chinese.", str, mch.Count.ToString()));

                return true;
            }
            else
            {
                Console.WriteLine("No chinese.");
                return false;
            }
        }
    }
}

原文地址:https://www.cnblogs.com/AloneSword/p/2237550.html