C# 检查字符串中是否只含有字母或者数字

在C#中要检查字符串是否只包含字母数字,我们可以使用正则表达式。
Regex类包含在system.text.regularexpressions命名空间中。
这里使用了ISMatch()方法,如果提供的提供的正则表达式匹配,则返回布尔结果。

让我们看一下以下行:

if (System.Text.RegularExpressions.Regex.IsMatch(str, @"^[a-zA-Z0-9]+$"))

sb.AppendLine("Example \"" + str + "\" is an alphanumeric string.");

else

sb.AppendLine("Example \"" + str + "\" is NOT an alphanumeric string.");

在ISmatch()方法中,首先提供了两个参数是字符串名称,它将与指定的正则表达式匹配,第二个是正则表达式与字符串将匹配。
如果字符串将与此正则表达式匹配,则ISmatch()方法将返回True值,否则为False值。

在C# 检查字符串中是否包含字母或者数字示例

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication8

{

    class Program

    {

        static void Main(string[] args)

        {

            string str1 = "xyz123";

            string str2 = "xyz&123";

 

            string[] array = { str1, str2 };

            StringBuilder sb = new StringBuilder();

            foreach (string str in array)

            {

                if (System.Text.RegularExpressions.Regex.IsMatch(str, @"^[a-zA-Z0-9]+$"))

                    sb.AppendLine("Example \"" + str + "\" is an alphanumeric string.");

                else

                    sb.AppendLine("Example \"" + str + "\" is NOT an alphanumeric string.");

            }

            Console.WriteLine(sb);

            Console.ReadLine();

        }

    }

}
日期:2020-04-11 22:50:16 来源:oir作者:oir