Using String.Format to build Regular Expressions: "Input string was not in a correct format"

1.6k Views Asked by At

I'm bulding document-from-template engine. At certain points I need to match on Reg Exp groups and replace template text with content from a db.

I 'hardcoded' my RegExp initially, doing something like:

Regex r = new Regex(@"{DocSectionToggle::(?<ColumnName>\w+)::(?<ResponseValue>.+)}\n\[\[(?<SectionContent>.+)\]\]", RegexOptions.Multiline);

Apologies: it does group capture, so the syntax isn't the prettiest.

Just to make things neater and because I want' to keep the patterns in web.config or elsewhere, I've 'evolved' algorithm to something like:

string _regexp_DocSectionToggle = @"{DocSectionToggle::{0}::{1}}\n\[\[{2}\]\]";

/* Reg Exp Patterns for group capture */

string _rxCol            = @"(?<{ColumnName}>\w+)";
string _rxResp           = @"(?<{ResponseValue}>.+)";
string _rxSectContent    = @"(?<{SectionContent}>.+)"; 

Regex r = new Regex( string.Format(_regexp_DocSectionToggle,
                                    _rxCol,
                                    _rxResp,
                                    _rxSectContent), 

                      RegexOptions.Multiline
                   );

But I'm getting an error: 'Input string was not in correct format'.

Can anyone tell my why? Is this a limitation of string.Format(...)?

Thanks for looking.

2

There are 2 best solutions below

1
On BEST ANSWER

The problem is the { and } which you don't want to mark format specifiers. IIRC, you just double them:

string _regexp_DocSectionToggle = @"{{DocSectionToggle::{0}::{1}}}\n\[\[{2}\]\]";
0
On

You need to escape { and } by using {{ and }} as the following:

string _regexp_DocSectionToggle = @"{{DocSectionToggle::{0}::{1}}}\n\[\[{2}\]\]";