C # String Format Regular Expression Placeholders

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

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

The first three letters, immediately after the start of the regular expression string (^), can be one of many possible combinations of alphabetic characters.

I want to make an elegant String.Format using the above, putting my 3 letter selection combination at the beginning and using this in my matching algorithm, for example:

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

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

The problem is that when I do String.Format, because I have other curly braces in the string (for example, \d{4} ) String.Format is looking for something that can be put here, cannot find it and gives I got a mistake

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

Does anyone know how, if I do not separate the lines, I can avoid other curly braces or something to avoid the above error?

+6
regex formatting
source share
1 answer

Try this (note the double curly braces):

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

+10
source share

All Articles