2009-08-26 34 views
2

我需要从字符串中提取邮政编码。字符串看起来像这样:需要帮助正则表达式从字符串中提取邮政编码

Sandviksveien 184, 1300 Sandvika 

如何使用正则表达式来提取邮政编码? 在上面的字符串的邮政编码是1300

我已经试过沿路是这样的:

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

但是,这是行不通的。

回答

6

这应该做的伎俩:

,\s(\d{4})

这里是如何使用它一个简单的例子:

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); 
    } 
} 
+0

噢,它看起来像这样的作品:)首先需要一些更多的测试: ) – Steven 2009-08-26 15:05:43

2

我认为你正在寻找分组,您可以用正则表达式做...

举一个例子......

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

您可能需要修改这个有点,因为我要去掉的记忆......

1

试试这个:

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); 
    } 
}