Compare Strings by format not by value

Asked

Viewed 107 times

7

I have a shape of a String, for example:

  • xxxx-xxxx-xxx

But instead of the x can enter several letters or numbers, example:

  • A216-0450-013
  • X2LP-1018-589
  • Y585-0000-047

What I need to do is compare to know if the format is equal, however the value does not matter.

  • And what is the format, specifically speaking? Anywhere can have a letter or a number?

  • @jbueno yes, anywhere, the format is the one I put, 4 digits, dash (-), 4 digits, dash (-), 3 digits

1 answer

8


Using the Regex.IsMatch() you can check if a string is within the expected pattern, below follows an implementation.


Don’t forget to include the namespace System.Text.RegularExpressions

Using system.Text.Regularexpressions;

string pattern = @"^.{4}-.{4}-.{3}$";
string[] input = { "A216-0450-013" , "X2LP-1018-589",   "Y585-0000-047" , "585-0000-047" };

foreach(var item in input)
{
    if(Regex.IsMatch(item,pattern))
        Console.WriteLine("{0} is Match",item);
    else
        Console.WriteLine("{0} does not Match",item);
}

See working on .Net Fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.