Remove text enclosed in div tag using C # Regex
I have a line as follows:
string chart = "<div id=\"divOne\">Label.</div>;"which is dynamically generated without my control and would like to delete the text "Shortcut". from the enclosing div element.
I tried the following, but my regex is still limited to make it work:
System.Text.RegularExpressions.Regex.Replace(chart, @"/(<div[^>]+>)[^<]+(<\/div>)/i", "");
Using LinqPad, I got this snippet. Hope it solves your problem correctly.
string chart = "<div id=\"divOne\">Label.</div>;";
var regex = new System.Text.RegularExpressions.Regex(@">.*<");
var result = regex.Replace(chart, "><");
result.Dump(); // prints <div id="divOne"></div>
, .
, , , . , node, MatchEvaluator. :
string pattern = @"<(?<element>\w*) (?<attrs>.*)>(?<contents>.*)</(?<elementClose>.*>)";
var x = System.Text.RegularExpressions
.Regex.Replace(chart, pattern, m => m.Value.Replace(m.Groups["contents"].Value, ""));
, , , . .
I am a little confused by your question; it is like you are parsing some pre-generated HTML and want to remove all instances of the value chartthat happen inside the tag <div>. If this is correct, try the following:
"(<div[^>]*>[^<]*)"+chart+"([^<]*</div>)"
Return the first and second groupings combined together, and you should have <div>back without chart.