| | 1 | | using System.Text.RegularExpressions; |
| | 2 | |
|
| | 3 | | public class CoordinateUtils |
| | 4 | | { |
| | 5 | | private const string COORDINATE_MATCH_REGEX = @"(?<!\w)(?<!<\/noparse>)[-]?\d{1,3},[-]?\d{1,3}(?!\w)(?!<\/\/noparse> |
| | 6 | | private const int MAX_X_COORDINATE = 163; |
| | 7 | | private const int MIN_X_COORDINATE = -150; |
| | 8 | | private const int MAX_Y_COORDINATE = 158; |
| | 9 | | private const int MIN_Y_COORDINATE = -150; |
| | 10 | |
|
| 1 | 11 | | private static readonly Regex REGEX = new (COORDINATE_MATCH_REGEX, RegexOptions.IgnoreCase); |
| | 12 | |
|
| | 13 | | public static bool IsCoordinateInRange(int x, int y) => |
| 5 | 14 | | x is <= MAX_X_COORDINATE and >= MIN_X_COORDINATE && y is <= MAX_Y_COORDINATE and >= MIN_Y_COORDINATE; |
| | 15 | |
|
| | 16 | | public delegate string CoordinatesReplacementDelegate(string matchedText, (int x, int y) coordinates); |
| | 17 | |
|
| | 18 | | public static string ReplaceTextCoordinates(string text, CoordinatesReplacementDelegate replacementCallback) |
| | 19 | | { |
| 12 | 20 | | return REGEX.Replace(text, match => |
| | 21 | | { |
| 5 | 22 | | string value = match.Value; |
| 5 | 23 | | int.TryParse(value.Split(',')[0], out int x); |
| 5 | 24 | | int.TryParse(value.Split(',')[1], out int y); |
| | 25 | |
|
| 5 | 26 | | return IsCoordinateInRange(x, y) ? replacementCallback.Invoke(value, (x, y)) : value; |
| | 27 | | }); |
| | 28 | | } |
| | 29 | |
|
| | 30 | | public static bool HasValidTextCoordinates(string text) |
| | 31 | | { |
| 0 | 32 | | MatchCollection matches = REGEX.Matches(text); |
| | 33 | |
|
| 0 | 34 | | foreach (Match match in matches) |
| | 35 | | { |
| 0 | 36 | | if (!match.Success) continue; |
| 0 | 37 | | string value = match.Value; |
| 0 | 38 | | int.TryParse(value.Split(',')[0], out int x); |
| 0 | 39 | | int.TryParse(value.Split(',')[1], out int y); |
| | 40 | |
|
| 0 | 41 | | if (IsCoordinateInRange(x, y)) |
| 0 | 42 | | return true; |
| | 43 | | } |
| | 44 | |
|
| 0 | 45 | | return false; |
| 0 | 46 | | } |
| | 47 | |
|
| | 48 | | public static ParcelCoordinates ParseCoordinatesString(string coordinates) => |
| 0 | 49 | | new (int.Parse(coordinates.Split(',')[0]), int.Parse(coordinates.Split(',')[1])); |
| | 50 | | } |