[英]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.
在上面的字符串中,邮政编码为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. 但这不起作用。
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);
}
}
I think you're looking for Grouping that you can do with RegExes... 我想你正在寻找可以用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... 你可能需要稍微修改一下因为我要记忆了......
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.