如何检查字符串是否包含一定数量的字母和数字C#

时间:2019-03-29 12:07:56

标签: c#

我想查看一个字符串是否包含3个字母+ 2个数字+ 1个字母或数字。这是当今瑞典车牌的标准。

是否可以查看字符串是否具有标准ABC123或ABC12D,并且最好按该顺序进行? 如何做到尽可能简单?

if(theString.Length == 6)
{
    if(theString.Contains(...)
    {

3 个答案:

答案 0 :(得分:9)

您应该为此使用正则表达式:

Regex r = new Regex("^[A-Z]{3}[0-9]{3}$");
// ^ start of string
// [A-Z] a letter
// {3} 3 times
// [0-9] a number
// {3} 3 times
// $ end of string

string correct = "ABC123";
string wrong = "ABC12B";

Console.WriteLine(correct + ": " + (r.IsMatch(correct) ? "correct" : "wrong"));
Console.WriteLine(wrong + ": " + (r.IsMatch(wrong) ? "correct" : "wrong"));

// If last character can also be a letter:
r = new Regex("^[A-Z]{3}[0-9]{2}[0-9A-Z]$");
// ^ start of string
// [A-Z] a letter
// {3} 3 times
// [0-9A-Z] a number
// {2} 2 times
// [0-9A-Z] A letter or a number
// $ end of string

Console.WriteLine(correct + ": " + (r.IsMatch(correct) ? "correct" : "wrong"));
Console.WriteLine(wrong + ": " + (r.IsMatch(wrong) ? "correct" : "wrong"));

答案 1 :(得分:2)

您可以使用Regex解决此问题:

if (Regex.IsMatch(theString, @"^[A-Z]{3}\d{2}(\d|[A-Z])$"))
{
    // matches both types of numberplates
}

答案 2 :(得分:1)

下面的代码将使用正则表达式进行检查

String input="ABC123";
var result = Regex.IsMatch(input, "^[A-Z]{3}[0-9]{3}$") || 
             Regex.IsMatch(input, "^[A-Z]{3}[0-9]{2}[A-Z]{1}$");
Console.WriteLine(result);