C # textbox auto formatting
I would like to provide users with a textbox with a fantastic key that will insert a dash. Key length must be 20 characters (4 groups of 5 characters)
I tried using regex, firstly:
Regex.Replace( text, ".{5}", "$0-" );
which is a problem because the dash is inserted even when there are no further characters, such as AAAAA-, which makes it impossible to remove the dash when it is automatically inserted.
then I thought that the following character should appear in the regex
Regex.Replace( text, "(.{5})(.)", "$1-$2" );
but which splits the key into a group of 5-6-6 ...
Any ideas?
source to share
Use negative to avoid adding one -
last time. It matches each of the five digits of the input string from the first but not the last 5 digits.
.{5}(?!$)
Replaced string
$0-
string str = "12345678909876543212";
string result = Regex.Replace(str, @".{5}(?!$)", "$0-");
Console.WriteLine(result);
Console.ReadLine();
Output:
12345-67890-98765-43212
source to share
The linq style method may be to your liking if you fancy a non-regex-specific way ...
This can be run in LinqPad:
var sourceReg = "abcdeFGHIJ12345klmno";
var splitLength=5;
var regList = Enumerable.Range(0, sourceReg.Length/splitLength).Select(i => sourceReg.Substring(i*splitLength, splitLength));
regList.Dump("Registration List");
var regSeparated = string.Join("-", regList);
regSeparated.Dump("Registration with Separators");
Note: Registries that are not precisely divided are not counted.
See method above plus others in a similar question:
source to share
code
string key = "12345678909876543212";
licenseBox.Text = System.Text.RegularExpressions.Regex.Replace(key, @".{5}(?!$)", "$0-");
"As above" should work fine.
And the following may work for you as well.
code
string key = "12345678909876543212";
licenseBox.Text = String.Format("{0}-{1}-{2}-{3}", key.Substring(0, 5), key.Substring(5, 5), key.Substring(10, 5), key.Substring(15, 5));
Output
12345-67890-98765-43212
source to share