Skip to content

Commit

Permalink
More regex translation
Browse files Browse the repository at this point in the history
  • Loading branch information
sjp committed Jun 9, 2024
1 parent f92d436 commit 09a24bb
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/SJP.Schematic.Reporting/IdentifierExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ private static string ToSlug(string input, int maxChars = 45)

var result = RemoveDiacritics(input).ToLowerInvariant();
// invalid chars
result = _invalidCharRegex.Replace(result, string.Empty);
result = InvalidCharRegex().Replace(result, string.Empty);
// convert multiple spaces into one space
result = _spaceCollapseRegex.Replace(result, " ").Trim();
result = SpaceCollapseRegex().Replace(result, " ").Trim();
// cut and trim
result = Truncate(result, maxChars).Trim();
// whitespace to hyphens
result = _whitespaceRegex.Replace(result, "-").Trim();
result = WhitespaceRegex().Replace(result, "-").Trim();
// underscore/period to hyphen
result = _underscorePeriodRegex.Replace(result, "-").Trim();
result = UnderscorePeriodRegex().Replace(result, "-").Trim();

// ensure chars are safe on disk
var invalidChars = Path.GetInvalidFileNameChars();
Expand All @@ -69,10 +69,17 @@ private static string ToSlug(string input, int maxChars = 45)
return new string(validChars);
}

private static readonly Regex _invalidCharRegex = new(@"[^a-z0-9\s-_.]", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
private static readonly Regex _spaceCollapseRegex = new(@"\s+", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
private static readonly Regex _whitespaceRegex = new("\\s", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
private static readonly Regex _underscorePeriodRegex = new("[_.]", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
[GeneratedRegex(@"[^a-z0-9\s-_.]", RegexOptions.Compiled, matchTimeoutMilliseconds: 100)]
private static partial Regex InvalidCharRegex();

[GeneratedRegex(@"\s+", RegexOptions.Compiled, matchTimeoutMilliseconds: 100)]
private static partial Regex SpaceCollapseRegex();

[GeneratedRegex("\\s", RegexOptions.Compiled, matchTimeoutMilliseconds: 100)]
private static partial Regex WhitespaceRegex();

[GeneratedRegex("[_.]", RegexOptions.Compiled, matchTimeoutMilliseconds: 100)]
private static partial Regex UnderscorePeriodRegex();

private static string RemoveDiacritics(string input)
{
Expand Down

0 comments on commit 09a24bb

Please sign in to comment.