Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

How do I use string.Format to enter a value into a regular expression, where that regular expression has curly-braces in it already to define repetition limitation? (My mind is cloudy from the collision for syntax)

e.g. The normal regex is "^\d{0,2}", and I wish to insert the '2' from the property MaxLength

like image 874
Overflew Avatar asked Nov 28 '09 01:11

Overflew


2 Answers

You can now use string interpolation to do it:

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

Again, you need to escape the curly braces by doubling them.

like image 131
Maxter Avatar answered Oct 19 '22 23:10

Maxter


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);
like image 39
Thomas Levesque Avatar answered Oct 19 '22 23:10

Thomas Levesque