7

I have a regular expression, defined in a verbatim C# string type, like so:

private static string importFileRegex = @"^{0}(\d{4})[W|S]\.(csv|cur)";

The first 3 letters, right after the regex line start (^) can be one of many possible combinations of alphabetic characters.

I want to do an elegant String.Format using the above, placing my 3-letter combination of choice at the start and using this in my matching algorithm, like this:

string regex = String.Format(importFileRegex, "ABC");

Which will give me a regex of ^ABC(\d{4})[W|S]\.(csv|cur)

Problem is, when I do the String.Format, because I have other curly braces in the string (e.g. \d{4}) String.Format looks for something to put in here, can't find it and gives me an error:

System.FormatException : Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Anyone know how, short of splitting the strings out, I can escape the other curly braces or something to avoid the above error?

ccellar
  • 10,326
  • 2
  • 38
  • 56
A. Murray
  • 2,761
  • 5
  • 27
  • 40

1 Answers1

11

Try this (notice the double curly braces):

@"^{0}(\d{{4}})[W|S]\.(csv|cur)"

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • What he said plus this question also covers it and the answer has an MSDN link: http://stackoverflow.com/questions/160742/how-do-you-put-and-in-a-format-string – J M Mar 23 '09 at 10:09
  • I always forget about the double curly braces. +1. – OregonGhost Mar 23 '09 at 10:24