scrubbing strings w/ regex

2007-11-26 @ 09:39#

for a lot of my work, i use a token-replacement pattern that looks like this:

<x:include href="/folder/path/$docid$?filter=$filter$" >

i make a pass at the code using a collection of name-value pairs that representing the currently defined arguments (usually all derived from the state of the web request) and replace the tokens w/ any state data i have available.

inevitably, some tokens are left over after the pass since not all state data would be available for every request. that leaves me with something that looks like this:

<x:include href="/folder/path/this-page.html?filter=$filter$" >

what i needed was a way to scrub the string of any 'left over' unresolved tokens. i used this regex to get the job done in one line of code:

contents = Regex.Replace(contents, @"(\$([^$]*)\$)", string.Empty,RegexOptions.IgnoreCase | RegexOptions.Multiline);

that leaves me with this:

<x:include href="/folder/path/this-page.html?filter=" >

nice and simple!