string.Format, regex + curly braces (C#)

Replace single curly braces with double curly braces:

string regex = string.Format(@"^\d{{0,{0}}}", MaxLength);

If that makes your eyes hurt you could just use ordinary string concatenation instead:

string regex = @"^\d{0," + MaxLength + "}";

You can escape curly braces by doubling them :

string.Format("Hello {{World}}") // returns "Hello {World}"

In your case, it would be something like that :

string regexPattern = string.Format("^\d{{0,{0}}}", MaxLength);

For details on the formatting strings, see MSDN

var regex = String.Format(@"^\d{{0,{0}{1}", this.MaxLength, "}")

And yes, the extra parameter is may be required (no, it's not in this case) due to the eccentricities of the way the braces are interpreted. See the MSDN link for more.

All in all, I have to agree with Mark, just go with normal string concatenation in this case.

Tags:

C#

Regex