FearlessFox
FearlessFox

Reputation: 174

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. 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? How do I do it as simple as possible?

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

Upvotes: 3

Views: 2616

Answers (3)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

The below code will check using 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);

Upvotes: 1

Nico Schreiner
Nico Schreiner

Reputation: 437

You could solve this using Regex:

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

Upvotes: 2

kara
kara

Reputation: 3455

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"));

Upvotes: 10

Related Questions