Regular expression and ampersand issues

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

Name: John Doe
Phone: 555-123-1234
Email: john.doe@url.com
Dept: DHS-A&I-MRB

      

Here is 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 had no luck with any of these options: "A & I" "[A] [&] [I],"

But when I am strictly user "&", the line turns red. Any suggestions?

Thanks Dan

+2


a source to share


2 answers


Regex looks great to me. I suspect that the text could be encoded like this:

A&I

      

at the entrance.



You can also do it gvrow.Cells[6].Text.Contains("A&I")

instead of regex. Or gvrow.Cells[6].Text.Contains("A&I")

if I am correct with the coding problem.

string.Contains is also faster than Regex.

You can also HttpUtility.HtmlDecode

in the text before checking for A & I.

+4


a source


Both of them successfully match:

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 Cells index is wrong)?

+1


a source







All Articles