Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created July 2, 2024 15:28
Show Gist options
  • Save karenpayneoregon/7aca458adc8365a971638477444c8d86 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/7aca458adc8365a971638477444c8d86 to your computer and use it in GitHub Desktop.
Format social security number

Given a string var value = "123458899"; Format with dashes ➡️ 123-45-8899

using System.Text.RegularExpressions;
public static partial class StringHelpers
{
public static string FormatSocial1(string value)
{
if (string.IsNullOrEmpty(value))
return value;
if (IsInteger(value) == false)
throw new ArgumentException("Invalid SSN");
return SplitRegex().Replace(value, "$1-$2-$3");
}
public static string FormatSocial2(string value)
{
if (string.IsNullOrEmpty(value))
return value;
if (IsInteger(value) == false)
throw new ArgumentException("Invalid SSN");
return $"{value[..3]}-{value[3..5]}-{value[^4..]}";
}
[GeneratedRegex(@"(\d{3})(\d{2})(\d{4})")]
private static partial Regex SplitRegex();
public static bool IsInteger(string value)
=> value.All(c => c is >= '0' and <= '9');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment