3

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?

pikausp
  • 1,142
  • 11
  • 31

4 Answers4

6

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

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
 .{5}[^$]

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

Replace by

  $0-

See demo.

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

vks
  • 67,027
  • 10
  • 91
  • 124
  • 2
    it works only if you put any character inside the not char class which wasn't present in the input string. `$` inside the char class matches a literal `$` symbol not the line end. see http://regex101.com/r/vY0rD6/4 – Avinash Raj Aug 27 '14 at 16:27
  • yups missed it completely . – vks Aug 27 '14 at 17:05
0

A linq style method might be to your liking if you fancy a non-regex way...

This can be ran 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: doesn't take into account reg codes that don't divide exactly.

See the method above plus others in a similar question:

Add separator to string at every N characters?

Community
  • 1
  • 1
j3r3m7
  • 742
  • 9
  • 21
0

Code

string key = "12345678909876543212";
licenseBox.Text = System.Text.RegularExpressions.Regex.Replace(key, @".{5}(?!$)", "$0-");

"As Mentioned Above" - Should work fine.

And the following might also work for you.

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
Maruata
  • 41
  • 7