This question already has answers here:
RegEx for matching UK Postcodes
(33 answers)
Closed 3 years ago.
I need to check the U.K postcode against a list.
The U.K postcode is of a standard format but the list only contains the outward section that I need to check against.
The list contains a series of outward postcode with also some data relating to this outward postcode, so for example
AL St Albans
B Birmingham
BT Belfast
TR Taunton
TR21 Taunton X
TR22 Taunton Y
My aim is that when I get a postcode, for example B20 7TP, I can search and find Birmingham.
Any ideas??
The question is different to the ones referred to as possible answers, but in my case I need to check a full postcode against just the outward postcode.
If you have the whole postcode and only want to use the outcode, remove the last three characters and use what remains. All postcodes end with the pattern digit-alpha-alpha, so removing those characters will give the outcode; any string that does not fit that pattern or that does not give a valid outcode after removing that substring is not a valid postcode. (Source)
If you're willing to take on an external (and Internet-based) dependency, you could look at using something like https://postcodes.io, in particular the outcodes section of that API. I have no affiliation with postcodes.io; I just found it after a Google.
Per the documentation, /outcodes will return
the outcode
the eastings
the northings
the andministrative counties under the code
the district/unitary authories under the code
the administrative/electoral areas under the code
the WGS84 logitude
the WGS84 latitude
the countries included in the code
the parish/communities in the code
For reference, a call to /outcodes/TA1 returns:
{
"status": 200,
"result": {
"outcode": "TA1",
"longitude": -3.10297767924529,
"latitude": 51.0133987332761,
"northings": 124359,
"eastings": 322721,
"admin_district": [
"Taunton Deane"
],
"parish": [
"Taunton Deane, unparished area",
"Bishop's Hull",
"West Monkton",
"Trull",
"Comeytrowe"
],
"admin_county": [
"Somerset"
],
"admin_ward": [
"Taunton Halcon",
"Bishop's Hull",
"Taunton Lyngford",
"Taunton Eastgate",
"West Monkton",
"Taunton Manor and Wilton",
"Taunton Fairwater",
"Taunton Killams and Mountfield",
"Trull",
"Comeytrowe",
"Taunton Blackbrook and Holway"
],
"country": [
"England"
]
}
}
If you have the whole postcode, the /postcodes endpoint will return considerably more detailed information which I will not include here, but it does include the outcode and the incode as separate fields.
I would, of course, recommend caching the results of any call to a remote API.
Build a regular expression from the list of known codes. Pay attention that the order of known codes in the regular expression matters. You need to use longer codes before shorter codes.
private void button1_Click(object sender, EventArgs e)
{
textBoxLog.Clear();
var regionList = BuildList();
var regex = BuildRegex(regionList.Keys);
TryMatch("B20 7TP", regionList, regex);
TryMatch("BT1 1AB", regionList, regex);
TryMatch("TR21 1AB", regionList, regex);
TryMatch("TR0 00", regionList, regex);
TryMatch("XX123", regionList, regex);
}
private static IReadOnlyDictionary<string, string> BuildList()
{
Dictionary<string, string> result = new Dictionary<string, string>();
result.Add("AL", "St Albans");
result.Add("B", "Birmingham");
result.Add("BT", "Belfast");
result.Add("TR", "Taunton");
result.Add("TR21", "Taunton X");
result.Add("TR22", "Taunton Y");
return result;
}
private static Regex BuildRegex(IEnumerable<string> codes)
{
// Sort the code by length descending so that for example TR21 is sorted before TR and is found by regex engine
// before the shorter match
codes = from code in codes
orderby code.Length descending
select code;
// Escape the codes to be used in the regex
codes = from code in codes
select Regex.Escape(code);
// create Regex Alternatives
string codesAlternatives = string.Join("|", codes.ToArray());
// A regex that starts with any of the codes and then has any data following
string lRegExSource = "^(" + codesAlternatives + ").*";
return new Regex(lRegExSource, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
/// <summary>
/// Try to match the postcode to a region
/// </summary>
private bool CheckPostCode(string postCode, out string identifiedRegion, IReadOnlyDictionary<string, string> regionList, Regex regex)
{
// Check whether we have any match at all
Match match = regex.Match(postCode);
bool result = match.Success;
if (result)
{
// Take region code from first match group
// and use it in dictionary to get region name
string regionCode = match.Groups[1].Value;
identifiedRegion = regionList[regionCode];
}
else
{
identifiedRegion = "";
}
return result;
}
private void TryMatch(string code, IReadOnlyDictionary<string, string> regionList, Regex regex)
{
string region;
if (CheckPostCode(code, out region, regionList, regex))
{
AppendLog(code + ": " + region);
}
else
{
AppendLog(code + ": NO MATCH");
}
}
private void AppendLog(string log)
{
textBoxLog.AppendText(log + Environment.NewLine);
}
Produces this output:
B20 7TP: Birmingham
BT1 1AB: Belfast
TR21 1AB: Taunton X
TR0 00: Taunton
XX123: NO MATCH
For your information, the regex built here is ^(TR21|TR22|AL|BT|TR|B).*
I need to parse this string with C# but don't know how. Would you advise me on a good way to get values from this string" Arrays "
["root",[["t-a2hICACK35I","isYktsZwEVMQ","r-isYktsZwEVMQ",[["global_config",null,null,null,null,[null,"[\"AOvVaw0H3zstE2R8Hh96uT8kZylb\\u0026ust\\u003d1511890102832262\",null,0,null,0,null,null,null,0,null,null,null,1,1,1,1,0,1,null,null,null,null,null,null,null,null,0,0,0,null,null,null,0,null,null,0,0,null,null,1,null,400,null,null,null,1,null,0,null,null,null,null,0,0,\"NONE\",null,4,\"Related image\",7,0,\"%1$d\\u0026nbsp;\\u0026#215;\\u0026nbsp;%2$d\",0,null,null,null,null,null,0,null,0,\"#222\",0,1,null,1,null,0,null,null,null,null,null,0,null,0,0,0]\n"]
]
,["group_config",null,null,null,null,[null,"[null,null,null,null,1,null,null,1]\n"]
]
,["image_group",null,null,null,null,[null,"[[[0,\"mdba4buxuK9BKM:\",[\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcRR2V_IL-Zh_LdrVzgBgvq6zcL68YSL01zNGsQJxXTo2cpXaqVz6A\",256,197]\n,[\"https://www.30grad.shop/item/images/11296/3000x3000/azet-kmngang-shirt-fastlife.jpg\",3000,2315]\n,null,0,{\"2001\":[]\n,\"2003\":[null,\"RXXHApKYqqq7RM\",\"https://www.30grad.shop/hersteller/kmn-gang/\",\"KMN Gang | 30° Shop\",\"KMN Gang Azet T-Shirt Fast Life\",null,null,null,null,null,null,null,\"30° Merchandise Shop\"]\n}]\n]\n]\n"]
]
]
]
,["t-cuCqGEujB5w","iP3_T8N4D_s8","r-iP3_T8N4D_s8",[["enable_close_for_background",null,null,null,null,[null,null,null,null,1]
]
,["initial_open",null,null,null,null,[null,null,null,null,null,0]
]
,["remain_in_lightbox_container",null,null,null,null,[null,null,null,null,0]
]
,["ux",null,null,null,null,[null,"[{\"220802553\":1}]\n"]
]
,["gsa",null,null,null,null,[null,"[{\"46740956\":0,\"244399487\":0}]\n"]
]
]
]
,["t-RHI35lUscno","igbzzOoE9k74","r-igbzzOoE9k74"]
,["t-3mFqq0A9uuY","iymxTruthWUk","r-iymxTruthWUk",[["hide_label_on_focus",null,null,null,null,[null,null,null,null,0]
]
]
]
,["t-mqWFpp0vPaI","iJcTl2Z4mNb0","r-iJcTl2Z4mNb0"]
,["t-mqWFpp0vPaI","iLi8ChEUFkT8","r-iLi8ChEUFkT8"]
,["t-mqWFpp0vPaI","iM4MogigWfMk","r-iM4MogigWfMk"]
]
]
The given string is a json array (not a json object)
You can use Newtonsoft.json (add the NuGet package to your solution) to parse it into a JArray and do whatever you want with it.
using System;
using Newtonsoft.Json.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var s = "[\"root\",[[\"t-a2hICACK35I\",\"isYktsZwEVMQ\",\"r-isYktsZwEVMQ\",[[\"global_config\",null,null,null,null,[null,\"[\\\"AOvVaw0H3zstE2R8Hh96uT8kZylb\\\\u0026ust\\\\u003d1511890102832262\\\",null,0,null,0,null,null,null,0,null,null,null,1,1,1,1,0,1,null,null,null,null,null,null,null,null,0,0,0,null,null,null,0,null,null,0,0,null,null,1,null,400,null,null,null,1,null,0,null,null,null,null,0,0,\\\"NONE\\\",null,4,\\\"Related image\\\",7,0,\\\"%1$d\\\\u0026nbsp;\\\\u0026#215;\\\\u0026nbsp;%2$d\\\",0,null,null,null,null,null,0,null,0,\\\"#222\\\",0,1,null,1,null,0,null,null,null,null,null,0,null,0,0,0]\\n\"]\r\n]\r\n,[\"group_config\",null,null,null,null,[null,\"[null,null,null,null,1,null,null,1]\\n\"]\r\n]\r\n,[\"image_group\",null,null,null,null,[null,\"[[[0,\\\"mdba4buxuK9BKM:\\\",[\\\"https://encrypted-tbn0.gstatic.com/images?q\\\\u003dtbn:ANd9GcRR2V_IL-Zh_LdrVzgBgvq6zcL68YSL01zNGsQJxXTo2cpXaqVz6A\\\",256,197]\\n,[\\\"https://www.30grad.shop/item/images/11296/3000x3000/azet-kmngang-shirt-fastlife.jpg\\\",3000,2315]\\n,null,0,{\\\"2001\\\":[]\\n,\\\"2003\\\":[null,\\\"RXXHApKYqqq7RM\\\",\\\"https://www.30grad.shop/hersteller/kmn-gang/\\\",\\\"KMN Gang | 30° Shop\\\",\\\"KMN Gang Azet T-Shirt Fast Life\\\",null,null,null,null,null,null,null,\\\"30° Merchandise Shop\\\"]\\n}]\\n]\\n]\\n\"]\r\n]\r\n]\r\n]\r\n,[\"t-cuCqGEujB5w\",\"iP3_T8N4D_s8\",\"r-iP3_T8N4D_s8\",[[\"enable_close_for_background\",null,null,null,null,[null,null,null,null,1]\r\n]\r\n,[\"initial_open\",null,null,null,null,[null,null,null,null,null,0]\r\n]\r\n,[\"remain_in_lightbox_container\",null,null,null,null,[null,null,null,null,0]\r\n]\r\n,[\"ux\",null,null,null,null,[null,\"[{\\\"220802553\\\":1}]\\n\"]\r\n]\r\n,[\"gsa\",null,null,null,null,[null,\"[{\\\"46740956\\\":0,\\\"244399487\\\":0}]\\n\"]\r\n]\r\n]\r\n]\r\n,[\"t-RHI35lUscno\",\"igbzzOoE9k74\",\"r-igbzzOoE9k74\"]\r\n,[\"t-3mFqq0A9uuY\",\"iymxTruthWUk\",\"r-iymxTruthWUk\",[[\"hide_label_on_focus\",null,null,null,null,[null,null,null,null,0]\r\n]\r\n]\r\n]\r\n,[\"t-mqWFpp0vPaI\",\"iJcTl2Z4mNb0\",\"r-iJcTl2Z4mNb0\"]\r\n,[\"t-mqWFpp0vPaI\",\"iLi8ChEUFkT8\",\"r-iLi8ChEUFkT8\"]\r\n,[\"t-mqWFpp0vPaI\",\"iM4MogigWfMk\",\"r-iM4MogigWfMk\"]\r\n]\r\n]";
var jArray = JArray.Parse(s);
Console.WriteLine(jArray.ToString());
}
}
}
I'm using Json.NET in a .NET 4.0 application in order to convert a JSON RESTful response into XML. I am running into issues converting JSON into XML if a JSON child key has a space.
So far, I am able to convert most JSON responses.
Here are example responses along with the code which I am using to generate the XML.
{
num_reviews: "2",
page_id: "17816",
merchant_id: 7165
}
And here is the response which is causing an error:
[
{
headline: "ant bully",
created_date: "2010/06/12",
merchant_group_id: 10126,
profile_id: 0,
provider_id: 10000,
locale: "en_US",
helpful_score: 1314,
locale_id: 1,
variant: "",
bottomline: "Yes",
name: "Jessie",
page_id: "17816",
review_tags: [
{
Pros: [
"Easy to Learn",
"Engaging Story Line",
"Graphics",
"Good Audio",
"Multiplayer",
"Gameplay"
]
},
{
Describe Yourself: [
"Casual Gamer"
]
},
{
Best Uses: [
"Multiple Players"
]
},
{
Primary use: [
"Personal"
]
}
],
rating: 4,
merchant_id: 7165,
reviewer_type: "Verified Reviewer",
comments: "fun to play"
},
{
headline: "Ok game, but great price!",
created_date: "2010/02/28",
merchant_group_id: 10126,
profile_id: 0,
provider_id: 10000,
locale: "en_US",
helpful_score: 1918,
locale_id: 1,
variant: "",
bottomline: "Yes",
name: "Alleycatsandconmen",
page_id: "17816",
review_tags: [
{
Pros: [
"Easy to Learn",
"Engaging Story Line"
]
},
{
Describe Yourself: [
"Frequent Player"
]
},
{
Primary use: [
"Personal"
]
},
{
Best Uses: [
"Kids"
]
}
],
rating: 3,
merchant_id: 7165,
reviewer_type: "Verified Reviewer",
comments: "This is a cute game for the kids and at a great price. Just don't expect a whole lot."
}
]
So far, I have been considering on creating a mapping of the JSON data to a C# object and generating XML for that class. However, is there a way to keep this dynamic? Or is there a way to treat spaces as %20 encodings?
This question is same as how to validate JSON string before converting to XML in C#
If you have any further queries, please let me know.
You can call XmlConvert.EncodeName, which will escape any invalid characters using _s.
For example, a space would become _x0020_.
You cannot have an XMLElement Name with a space in it. You would need to replace the space with an Underscore or anyother element. If that is not feasible for you, try putting that value as an attribute for that Node.
I hope this makes sense.