string.Format, regex + curly braces (C#)
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
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.
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.
精彩评论