我想看看一个字符串是否包含 3 个字母 + 2 个数字 + 1 个字母或数字。这是当今瑞典车牌的标准。
是否可以查看字符串是否符合标准 ABC123 或 ABC12D 并且最好按该顺序? 如何尽可能简单地做到这一点?
if(theString.Length == 6)
{
if(theString.Contains(...)
{
最佳答案
你应该为此使用正则表达式:
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"));
关于c# - 如何检查字符串是否包含一定数量的字母和数字 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417138/