Steven
Steven

Reputation: 19425

Need help with Regex to extract zip code from string

I need to extract the zip code from a string. The string looks like this:

Sandviksveien 184, 1300 Sandvika

How can I use regex to extract the zip code? In the above string the zip code would be 1300.

I've tried something along the road like this:

Regex pattern = new Regex(", [0..9]{4} ");
string str = "Sandviksveien 184, 1300 Sandvika";
string[] substring = pattern.Split(str);
lblMigrate.Text = substring[1].ToString();

But this is not working.

Upvotes: 3

Views: 5871

Answers (3)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

Try this:

var strs = new List<string> { 
"ffsf 324, 3480 hello",
"abcd 123, 1234 hello",
"abcd 124, 1235 hello",
"abcd 125, 1235 hello"
};

Regex r = new Regex(@",\s\d{4}");

foreach (var item in strs)
{
    var m = r.Match(item);
    if (m.Success)
    {
       Console.WriteLine("Found: {0} in string {1}", m.Value.Substring(2), item);
    }
}

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351486

This ought to do the trick:

,\s(\d{4})

And here is a brief example of how to use it:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        String input = "Sandviksveien 184, 1300 Sandvika";

        Regex regex = new Regex(@",\s(\d{4})",
            RegexOptions.Compiled |
            RegexOptions.CultureInvariant);

        Match match = regex.Match(input);

        if (match.Success)
            Console.WriteLine(match.Groups[1].Value);
    }
}

Upvotes: 6

hugoware
hugoware

Reputation: 36397

I think you're looking for Grouping that you can do with RegExes...

For an example...

Regex.Match(input, ", (?<zipcode>[0..9]{4}) ").Groups["zipcode"].Value;

You might need to modify this a bit since I'm going off of memory...

Upvotes: 3

Related Questions