我想查看一个字符串是否包含3个字母+ 2个数字+ 1个字母或数字。这是当今瑞典车牌的标准。
是否可以查看字符串是否具有标准的ABC123或ABC12D,并且最好以此顺序进行?如何做到尽可能简单?
if(theString.Length == 6)
{
if(theString.Contains(...)
{
Run Code Online (Sandbox Code Playgroud)
您应该为此使用正则表达式:
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"));
Run Code Online (Sandbox Code Playgroud)