Apply mask to string

I am reading the row id value from a table. When the identifier was entered by the user, this was done using the input mask that the user defined, so the mask could be something like 000-00-0000 , ##-###### , AA-9999999 , etc. The mask will be different from the user, and therefore must be evaluated at runtime.

Given that only alphanumeric text is stored in the table, what is the best way to create a new line using this mask?

For example:

Table value = "123456789"

If the user defined the mask 000-00-0000 , I want to get the line 123-45-6789 .

If the user defined the mask AA-9999999 , I want to get the line 12-3456789 .

If the user defined the mask FR999_999999 , I want to get the string FR123_456789 .

+7
source share
2 answers

This is what I need. The only drawback is that it ties me to the Windows Forms build.

  MaskedTextBox mtb = new MaskedTextBox("FR999_999999"); mtb.Text = "123456789"; return mtb.Text; 
+1
source

It seems that the mask template is that it inserts the corresponding dashes for each dash in the mask. If this is the case, then this should work.

 public static string MaskValue(string mask, string value) { var builder = new System.Text.StringBuilder(); var maskIndex = 0; var valueIndex = 0; while (maskIndex < mask.Length && valueIndex < value.Length) { if (mask[maskIndex] == '-') { builder.Append('-'); maskIndex++; } else { builder.Append(value[valueIndex]); maskIndex++; valueIndex++; } } // Add in the remainder of the value if (valueIndex + 1 < value.Length) { builder.Append(value.Substring(valueIndex); } return builder.ToString(); } 
+6
source

All Articles