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?

+3


source to share


4 answers


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-

      

DEMO



string str = "12345678909876543212";
string result = Regex.Replace(str, @".{5}(?!$)", "$0-");
Console.WriteLine(result);
Console.ReadLine();

      

Output:

12345-67890-98765-43212

      

IDEONE

+6


source


 .{5}[^$]

      

Use this.This will not put a - at the end.

Replaced by



  $0-

      

See demo.

http://regex101.com/r/vY0rD6/3

0


source


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:

Add a delimiter to the string at every N characters?

0


source


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

      

0


source







All Articles