[英]How to check if string contains certain amounts of letters and numbers C#
I'd like to see if a string contains 3 letters + 2 numbers + 1 letter or number. 我想看看一个字符串是否包含3个字母+2个数字+ 1个字母或数字。 This is the standard of a Swedish license plate nowadays. 这是现今瑞典车牌的标准。
Is it possible to see if the string got the standard ABC123 or ABC12D and preferably in that order? 是否有可能看到字符串是否符合标准ABC123或ABC12D,并且最好是按顺序? How do I do it as simple as possible? 我该如何做到尽可能简单?
if(theString.Length == 6)
{
if(theString.Contains(...)
{
You should use Regex for this: 您应该使用正则表达式:
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"));
You could solve this using Regex
: 您可以使用Regex
解决此问题:
if (Regex.IsMatch(theString, @"^[A-Z]{3}\d{2}(\d|[A-Z])$"))
{
// matches both types of numberplates
}
The below code will check using Regex 以下代码将使用Regex进行检查
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.