tags:

views:

807

answers:

3

Hi all.

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

Thanks.

+2  A: 

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);
Thomas Levesque
+9  A: 

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 + "}";
Mark Byers
the string concatenation makes *my* eyes hurt ;)
Thomas Levesque
If you don't like either of those, another option could be @"^\d{0,$MaxLength}".Replace("$MaxLength", MaxLength.ToString()). I'm not sure I like that myself because it's not C#-like, but it does keep the regular expression in readable form.
Mark Byers
+2  A: 

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.

Matthew Scharley
you're missing a closing curly brace ;)
Thomas Levesque
No I'm not ;) Caught that one quickly.
Matthew Scharley