views:

174

answers:

2

Hi All,

I'm having a bit of trouble with regex's (C#, ASP.NET), and I'm pretty sure I'm doing something fundamentally wrong. My task is to bind a dynamically created gridview to a datasource, and then iterate through a column in the grid, looking for the string "A&I". An example of what the data in the cell (in template column) looks like is:

Name: John Doe
Phone: 555-123-1234
Email: [email protected]
Dept: DHS-A&I-MRB

Here's the code I'm using to find the string value:

foreach(GridViewRow gvrow in gv.Rows)
{
   Match m = Regex.Match(gvrow.Cells[6].Text,"A&I");

   if(m.Success)
   {
      gvrow.ForeColor = System.Drawing.Color.Red;
   }
}

I'm not having any luck with any of these variations: "A&I" "[A][&][I]"

But when I strictly user "&", the row does turn red. Any suggestions?

Thanks, Dan

+1  A: 

Both of these match successfully:

Match m = Regex.Match("DHS-A&I-MRB", "A&I");
Match m0 = Regex.Match("DHS-A&I-MRB", @"A\&I");

Debug.WriteLine("m.Success = " + m.Success.ToString());
Debug.WriteLine("m0.Success = " + m0.Success.ToString());

Output:

m.Success = True
m0.Success = True

Perhaps the problem is elsewhere (possibly the wrong Cells index)?

Austin Salonen
I used that exact example, and they tested true. However, when testing the gridview output, they would fail. I think the problem is the encoding -- I just tested "A) Thanks for the suggestion, though. )
ajax81
+4  A: 

The Regex looks fine to me. I suspect the text to perhaps be encoded like:

A&I

on the input.

You could also do gvrow.Cells[6].Text.Contains("A&I") instead of regex. Or gvrow.Cells[6].Text.Contains("A&I") if I'm right with the encoding issue.

string.Contains is also faster than Regex.

You could also HttpUtility.HtmlDecode on the text before checking for the occurance of A&I.

Mikael Svenson
ajax81