0

I'm using the regex that I found from another stackoverflow-post from the postal code of the netherlands.

My code(in class UserContainer, but that shouldn't matter):

public bool CheckZip(string input)
{
     return Regex.IsMatch(input, "/^[1-9][0-9]{3}?(?!sa|sd|ss)[a-z]{2}$/i");
}

unit test (returns false):

[TestMethod()]
public void ZipCheckTest()
{
    string zip = "1001AA";

    Assert.IsTrue(container.CheckZip(zip));
}

I'm really new to regex, so can someone tell me what I'm doing wrong?

zhrgci
  • 584
  • 1
  • 6
  • 25
  • 3
    Regex literal notation inside a string literal is wrong: C# does not let you use regex literals. Use the pattern only as a string literal to instantiate a regex pattern and use `RegexOptions.IgnoreCase` as an option instead of a `i` flag. I.e. `Regex.IsMatch(input, "^[1-9][0-9]{3}(?!sa|sd|ss)[a-z]{2}$", RegexOptions.IgnoreCase)`. `{3}?` = `{3}` by the way. Also, `(?!sa|sd|ss)` = `(?!s[ads])` – Wiktor Stribiżew Nov 26 '19 at 08:30
  • @WiktorStribiżew So if I'm understanding correctly the good practice-way to do it is put the pattern in a string and than use that string with regex? – zhrgci Nov 26 '19 at 08:40
  • 1
    C# only allows you to define a regex pattern via a string. Be it a regular or verbatim string literal, it is not important. Slashes are part of the regex pattern in this case. – Wiktor Stribiżew Nov 26 '19 at 08:44

0 Answers0