-1

I am currently working on a project where the current Regular Expression being used for Zip Codes is "\d{5}(-\d{4})?" and the following test cases pass.

  1. 12345-1000
  2. 12345
  3. 123451231
  4. 12345-123
  5. 12345adfe

However, when I use the Regular Expression "^[0-9]{5}(?:-[0-9]{4})?$", only the following test cases pass

  1. 12345
  2. 12345-1234

The above is the correct behavior as following Zip codes standards.

  • Clearly the issue is solved, but I was wondering if someone could explain why this is the case?
  • Am I misunderstanding how "\d" works when I say that it uses digits 0-9?
  • What am I doing differently that FluentValidation uses the first regex differently than the Data Annotations do?
Darren
  • 29
  • 7
  • your first regex should not work for the cases "123451231" and "12345adfe". Atleast not everything. Are you sure these are capturing the whole thing, not first half? – Dunura Dulshan Jul 21 '22 at 16:11

2 Answers2

0

Try following :

            string[] zipCodes = { "12345-1000", "12345", "123451231", "12345-123", "12345adfe" };

            string pattern = @"^\d{5}-?[0-9a-zA-Z]{0,4}";

            foreach(string zipCode in zipCodes)
            {
                Match match = Regex.Match(zipCode, pattern);
                Console.WriteLine("Zipcode : {0}, Matched : {1}", zipCode, match.Success ? "Matched" : "Did Not Match");
            }
            Console.ReadLine();
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

They are not the same regex. The second expression is using the anchor tokens ^,$.

Your regex in action shows how your first expression matches and then you will see why adding the anchor tokens (specifically $) causes the expression to only match the two later examples provided.

Hank
  • 1,976
  • 10
  • 15