Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat regex will match text excluding what lies within HTML tags?
    primarykey
    data
    text
    <p>I am writing code for a search results page that needs to highlight search terms. The terms happen to occur within table cells (the app is iterating through GridView Row Cells), and these table cells may have HTML.</p> <p>Currently, my code looks like this (relevant hunks shown below):</p> <pre><code>const string highlightPattern = @"&lt;span class=""Highlight""&gt;$0&lt;/span&gt;"; DataBoundLiteralControl litCustomerComments = (DataBoundLiteralControl)e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Controls[0]; // Turn "term1 term2" into "(term1|term2)" string spaceDelimited = txtTextFilter.Text.Trim(); string pipeDelimited = string.Join("|", spaceDelimited.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)); string searchPattern = "(" + pipeDelimited + ")"; // Highlight search terms in Customer - Comments column e.Row.Cells[CUSTOMERCOMMENTS_COLUMN].Text = Regex.Replace(litCustomerComments.Text, searchPattern, highlightPattern, RegexOptions.IgnoreCase); </code></pre> <p>Amazingly it works. BUT, sometimes the text I am matching on is HTML that looks like this:</p> <pre><code>&lt;span class="CustomerName"&gt;Fred&lt;/span&gt; was a classy individual. </code></pre> <p>And if you search for "class" I want the highlight code to wrap the "class" in "classy" but of course not the HTML attribute "class" that happens to be in there! If you search for "Fred", that should be highlighted.</p> <p>So what's a good regex that will make sure matches happen only OUTSIDE the html tags? It doesn't have to be super hardcore. Simply making sure the match is not between &lt; and > would work fine, I think.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload