I'd like to provide users with a fancy license key textbox, that would insert the dashes. The key is supposed to be 20 characters long ( 4 groups of 5 characters )
I tried using regex, first:
Regex.Replace( text, ".{5}", "$0-" );
that is a problem as the dash is inserted even when there's no following characters, e.g AAAAA-, that results in not being able to remove the dash as it's automatically re-inserted.
then I thought about telling the regex there should be a following character
Regex.Replace( text, "(.{5})(.)", "$1-$2" );
but that splits the key into group of 5-6-6...
Any ideas?
Use a negative lookahead to avoid - to be added at the last. It matches each 5 digits of input string from the first but not the last 5 digits.
.{5}(?!$)
Replacement string
$0-
DEMO
string str = "12345678909876543212";
string result = Regex.Replace(str, @".{5}(?!$)", "$0-");
Console.WriteLine(result);
Console.ReadLine();
Output:
12345-67890-98765-43212
IDEONE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With