tags:

views:

51

answers:

1

Need some help, I have a regular expression that appears to work just fine when I put the pattern and string to parse into regexlib's tester. However, when I put it into C#, the same does not happen, no match.

Here is my match pattern, have tried both:

string regPattern = "\\{\\$([^\\$\\}]+)\\$\\}";

My string to parse comes from a database and is put into a variable after using ToString(). Here is a sample of the string (using Text Visualizer in VS2008) that works at regextlib but not in C#.

<p>1.Age?: -- Select One --<br />
2.HowFindProduct?: Friend/Relative Recommendation<br />
3.Influencers?: {$InfluencedDecision$}<br />
4.WherePurchase?: Office Superstore - i.e. Staples_ Office Depot_ Of<br />
5.ReplacementProduct?: This is a replacement to my previous product<br />
6.OtherBrands?: {$OtherBrands$}<br />
7.Income?: -- Select One --<br />
FirstName: John<br />
Initial: H<br />
LastName: Smith<br />
Address1: 123 any street<br />
Address2: suite 2<br />
City: any city<br />
State: CA<br />
ZipCode: 55555<br />
Country: usa<br />
EmailAddress: [email protected]<br />
Phone#: 714-555-1212<br />
ModelNumber: AXXXX<br />
SerialNumber: 23123d234s2s<br />
DateofPurchase: 09/09/2009<br />
NotifyMe1: on<br />
NotifyMe2: on</p>

And while simple, if it helps, here is the code I am using:

string regPattern = "\\{\\$([^\\$\\}]+)\\$\\}";
Regex.Replace(bodytext.ToString(), regPattern, "",RegexOptions.Multiline);

I have also tried declaring pattern using @ and Regex.Escape. Need some help here.

Any ideas?

+1  A: 

Well, your second statement is currently fairly pointless because you're ignoring the return value. Don't forget that strings are immutable - calling Regex.Replace won't change any existing strings; it will return a new string with the appropriate replacement operations performed. If you do this:

string regPattern = "\\{\\$([^\\$\\}]+)\\$\\}";
string replacedText = Regex.Replace(bodytext.ToString(), regPattern, 
                                    "", RegexOptions.Multiline);

then replacedText is the original with things like {$OtherBrands$} removed - I've tried that in a test program. If that's not what you wanted, please give more information about what you're actually trying to do.

Having said that, your regular expression pattern would be clearer using a verbatim string literal:

string regPattern = @"\{\$([^\$\}]+)\$\}";
Jon Skeet
Sorry about that, typed that up for the example (in VS have a lot more going on). I will give your expression a try. Thanks for the help!
davlun
Holy Toledo Batman! Nothing like missing the obvious in my original code. I was far too focused in the pattern as an issue that I missed the assignment logic that ran later in an if block had not execution path. You probably saved me a lot of time before I would have noticed that.
davlun