views:

2081

answers:

1

Hi All, 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?

Cheers, Andy

+6  A: 

Try this (notice the double curly braces):

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

Andrew Hare
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
I always forget about the double curly braces. +1.
OregonGhost