I spent about 3 hours trying to create a regular expression to check the coordinate line, which is home (but based on MGRS). I always had a rough time with a regular expression, and it started to make me bang my head on my desk.
Usually I don’t ask for something specific, but none of my friends who are familiar with regular expressions could help, and my own research / attempts to study at this stage drag on for too long.
How can I create a regex to test the following (or is it even possible to do this)?
AZ AA 0123456789 0123456789 HG-20
- All spaces are optional
- The first and second set of 2 characters are case insensitive, but must be az and be 2 characters for each section (first is the grid zone identifier, the second is the subsection identifier).
- The character part to the east and north can be of any arbitrary length if the total number of digits between the two “sections” is equal (for example, “1 1” is valid, “04563213245 54986187995 is really, 5598 549” is invalid). This is the part in which I really do not understand.
- "H" is required, but case insensitive (this is a separator for the height component in the coordinate line)
- "G" is optional (it indicates whether to use the location height or not when converting to Unity coordinates)
- - float, . , .
- . "H", ( , 2 ).
# System.Text.RegularExpressions regex.
, , . , ( , ).
:
/^[a-z]{2}\s?[a-z]{2}\s?\d+\s?\d+\s?hg?[-+]?\d+.?\d+?/ig
, , , ( H... ...).
, , ( InvalidArgument ArgumentOutOfRange, Location). , juju, regex, .
:
AZ AA 012345 012345 HG-20 ()AZAA 012345 012345 HG-20 ()AZAA012345012345HG-20 ()AZ AA 012345 012345 ()AZ AA 012345 01234 (, - ).AZ AA 012345 012345 HG (, , "H" )AZ AA 012345 012345 H (, , "H" )
!
, - , :
public Location(string coordinateString)
{
var stripped = coordinateString.ToUpper().Replace(" ", "");
var gridZonedesignator = stripped.Substring(0, 2);
var subLocationId = stripped.Substring(2, 2);
var identifiersRemoved = stripped.Remove(0, 4);
var heightParsed = identifiersRemoved.Split('H');
float height = 0;
bool useGroundHeight = false;
if (heightParsed.Length > 1)
{
if (heightParsed[1].StartsWith("G"))
{
useGroundHeight = true;
heightParsed[1] = heightParsed[1].Remove(0);
}
height = float.Parse(heightParsed[1], CultureInfo.InvariantCulture);
}
var accuracy = heightParsed[0].Length / 2;
var eastingString = heightParsed[0].Substring(0, accuracy).PadRight(4,'0');
var northingString = heightParsed[0].Substring(accuracy, accuracy).PadRight(4,'0');
CoordinateString = coordinateString;
GridZoneDesignation = gridZonedesignator;
SubLocationId = subLocationId;
Easting = eastingString;
EastingInt = int.Parse(Easting);
Northing = northingString;
NorthingInt = int.Parse(Northing);
IsStartFromGroundHeight = useGroundHeight;
Height = height;
}