| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="SnakeCasingTransform.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Globalization; |
| | | 9 | | using System.Text.RegularExpressions; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Text.TextCasing; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Transforms a string to snake_case. |
| | | 15 | | /// </summary> |
| | | 16 | | public sealed partial class SnakeCasingTransform : ITextCasingTransform |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Initializes a new instance of the <see cref="SnakeCasingTransform"/> class. |
| | | 20 | | /// </summary> |
| | 36 | 21 | | internal SnakeCasingTransform() { } |
| | | 22 | | |
| | | 23 | | /// <inheritdoc/> |
| | | 24 | | public string Apply(string input, CultureInfo culture) |
| | | 25 | | { |
| | 45 | 26 | | ArgumentNullException.ThrowIfNull(input); |
| | 45 | 27 | | ArgumentNullException.ThrowIfNull(culture); |
| | | 28 | | |
| | 45 | 29 | | return NormalizeSeparatorsRegex() |
| | 45 | 30 | | .Replace(UpperLowerBoundaryRegex().Replace(AcronymBoundaryRegex().Replace(input, "$1_$2"), "$1_$2"), "_") |
| | 45 | 31 | | .ToLower(culture); |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | [GeneratedRegex("[-\\s]")] |
| | | 35 | | private static partial Regex NormalizeSeparatorsRegex(); |
| | | 36 | | |
| | | 37 | | [GeneratedRegex(@"([\p{Ll}\d])([\p{Lu}])")] |
| | | 38 | | private static partial Regex UpperLowerBoundaryRegex(); |
| | | 39 | | |
| | | 40 | | [GeneratedRegex(@"([\p{Lu}]+)([\p{Lu}][\p{Ll}])")] |
| | | 41 | | private static partial Regex AcronymBoundaryRegex(); |
| | | 42 | | } |
| | | 43 | | |