Given a string var value = "123458899";
Format with dashes ➡️ 123-45-8899
Created
July 2, 2024 15:28
-
-
Save karenpayneoregon/7aca458adc8365a971638477444c8d86 to your computer and use it in GitHub Desktop.
Format social security number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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