Label.;"which is dynamically...">

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", "");

+3
source share
6 answers

Your regex looks good to me (but don't specify delimiters and modifiers '/.../i'). And use '$1$2'as a replacement string:

var re = new System.Text.RegularExpressions.Regex(@"(?i)(<div[^>]+>)[^<]+(<\/div>)");
var text = regex.Replace(text, "$1$2");
+1
source

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, ""));

, , , . .

+2

:

<div\b[^>]*>(.*?)<\/div>

<div></div>

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<div\b[^>]*>(.*?)<\/div>");
Console.WriteLine(regex.Replace("<div>Label 1.</div>","<div></div>"));
Console.ReadLine();
+1

div.

Regex.Replace(chart,yourPattern,string.empty);
0

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.

0
source

Here is a better way than Regex.

var element = XElement.Parse("<div id=\"divOne\">Label.</div>");
element.Value = "";
var value = element.ToString();

Open RegEx tags except XHTML tags contained offline

0
source

All Articles