Search code examples
c#regexmatchzipcode

Why can't Regex match Zip Code pattern in Richtextbox1


How come it can't find the Zip code pattern inside richtextbox1? Can't regex look around the richtextbox and find it?

This is the code I used:

string text = richTextBox1.Text.ToString();
Regex regex = new Regex(@"^\d{5}(?:[-\s]\d{4})?$");

foreach (Match match in regex.Matches(text))
{
    richTextBox2.Text += match;
}

This is the text inside richtextbox1

Mr. Underpants
6666 E River Park Dr
South Lake, CA 96150-5117
United States

Solution

  • The problem is you are "anchoring" the regex by using the beginning of input (^) and end of input ($) metacharacters.

    What you are saying, in essense, is match nothing BUT a zip code (with no surrounding text). Just remove the anchoring characters, and your solution will work:

    \d{5}(?:[-\s]\d{4})?