benscode-StitcherApi/Services/Utilities/CoordinateParser.cs

53 lines
1.5 KiB
C#
Raw Permalink Normal View History

2025-07-31 19:39:06 +07:00
using System.Text.RegularExpressions;
namespace StitcherApi.Services.Utilities;
public static class CoordinateParser
{
private static readonly Regex CoordRegex = new(
@"([A-Z]+)(\d+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase
);
public static (int MinRow, int MinCol, int MaxRow, int MaxCol) ParseCanvasRect(string rect)
{
if (string.IsNullOrEmpty(rect))
{
throw new ArgumentException("canvas_rect cannot be null or empty.");
}
string[] parts = rect.Split(':');
2025-07-31 19:39:06 +07:00
if (parts.Length != 2)
{
throw new ArgumentException("Invalid canvas_rect format.");
}
(int row1, int col1) = ParseSingleCoordinate(parts[0]);
(int row2, int col2) = ParseSingleCoordinate(parts[1]);
2025-07-31 19:39:06 +07:00
return (
Math.Min(row1, row2),
Math.Min(col1, col2),
Math.Max(row1, row2),
Math.Max(col1, col2)
);
}
private static (int Row, int Col) ParseSingleCoordinate(string coord)
{
Match match = CoordRegex.Match(coord);
2025-07-31 19:39:06 +07:00
if (!match.Success)
{
throw new ArgumentException($"Invalid coordinate format: {coord}");
}
string rowStr = match.Groups[1].Value.ToUpper();
string colStr = match.Groups[2].Value;
2025-07-31 19:39:06 +07:00
int row = rowStr.Length == 1 ? rowStr[0] - 'A' : 26 + (rowStr[1] - 'A');
int col = int.Parse(colStr) - 1;
return (row, col);
}
}