I'm trying to extract and replace or remove sections of a customised HTML document.
<div>
stuff I want to keep
</div>
<i class="special_i">@if includesDownloadables</i>
This is some stuff I want to replace on a certain condition.
<i class="special_i">@endif includesDownloadables</i>
<div>
More stuff to keep
</div>
<i class="special_i">@if instantDownload</i>
More stuff that is conditional.
<i class="special_i">@endif instantDownload</i>
<div>
More stuff to keep
</div>
I have been messing on regex101.com and experimenting myself, with this:
string condition = "includesDownloadables";
string pattern = @"<i\s.*?(@if {key}).*?(@endif {key}<\/i>)";
Regex regex = new Regex(pattern.Replace("{key}", condition ), RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
string MyString = "All the html to read";
MyString = regex.Replace(MyString , "");
The end point of my Regex seems to be working, but it is matching from the first instance of any tag, not specifically the one containing the condition I am looking for.
NOTE; this must also be able to take into account the tag have any attributes.
So how can I make it match from the start of an tag which contains the text @if MyCondition where the tag can have any data, style or class attributes and only if the tag contains the text I am looking for?
<i\b(?:(?!<i\b).)*?(@if {key}\b).*?(@endif {key}<\/i>), withsflag (or replace all.with[\s\S]). Or better yet, reconsider using specified parser for you syntax.