Hello编程员:)我需要帮助我的代码使用C#提取城市名称和UK PostCode只有来自地址字符串示例的那些UPPERCASE:
输入
15 Arnott Blk C Quadrant MOTHERWELL ML1 3TQ North Lanarkshire
Flat 3 2A Klea Avenue LONDON SW4 9JA London
12 Parish Close Dawley TELFORD TF4 3ER Shropshire
76 Admiralty Close WEST DRAYTON UB7 9NJ West Drayton
56 Glenburn Avenue MOTHERWELL ML1 5EF North Lanarkshire
25 Thirleby Road EDGWARE HA8 0HF Edgware
21 Prideaux Place Friars Place Lane LONDON W3 7AS London
1 Arnold Road STAINES-UPON-THAMES TW18 1LY Surrey
6 A Queen Street BRIDGWATER TA6 3DA Somerset Flat
8-B Lynn Court Mitcham Lane LONDON SW16 6LL London
35 Weirside Gardens WEST DRAYTON UB7 7TL
473 Rochfords Gardens SLOUGH SL2 5XF Berkshire
155 Strawberry Fields ADDLESTONE KT15 1FJ Surrey
输出
MOTHERWELL ML1 3TQ
LONDON SW4 9JA
TELEFORD TF4 3ER
WEST DRAYTON UB79NJ
MOTHERWELL ML1 5EF
EDGWARE HA8 0HF
LONDON W3 7AS
STAINE-UPON-THAMES TA6 3DA
LONDON SW16 6LL
WEST DRAYTON UB7 7TL
SLOUGH SL2 5XF
ADDLESTONE KT15 1FJ
它们是我需要提取的修复大写。非常感谢任何帮助或提示。
答案 0 :(得分:2)
using System.Text.RegularExpressions;
和
string FindCityAndCode(string input)
{
Regex regCode = new RegEx("([-A-Z ]{2,} [A-Z0-9]{2,} [A-Z0-9]{2,}) ");
var m = regCode.Match(input);
if (m.Success)
return m.Groups[1].Value;
return string.Empty;
}
正则表达式旨在匹配一系列大写的AZ和空格,后跟一个空格,然后至少两个字符AZ或0-9另一个空格,然后另外两个或多个字符AZ或0-9后跟另一个空间。
如果该表达式匹配,我们将返回它,否则我们返回一个空字符串......
我对英国邮政编码不太熟悉,因此{2,}
可能需要进一步限定,可能{2,3}
说2到3个字符......
答案 1 :(得分:0)
你好@Ubercoder我试过你的代码虽然有些邮政编码没有经过验证因此没有产生任何输出或不完整我有我的UKPost RegEx验证码如果你可以在你的代码中加入它可能有助于提取大写城市和邮政编码< / p>
public static bool IsPostCode(string postcode)
{
return (
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][0-9][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][0-9][A-HJKS-UWa-hjks-uw][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y][0-9][A-Za-z][ ]*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)") ||
Regex.IsMatch(postcode, "(^[Gg][Ii][Rr][]*0[Aa][Aa]$)")
);
}