Regex to analyze html from CDATA with C #

I would like to parse any HTML data that is returned in CDATA.

As an example <![CDATA[<table><tr><td>Approved</td></tr></table>]]>

Thanks!

+3
source share
6 answers

The expression to process your example will be

\<\!\[CDATA\[(?<text>[^\]]*)\]\]\>

If the group "text" will contain your HTML.

C # code you need:

using System.Text.RegularExpressions;
RegexOptions   options = RegexOptions.None;
Regex          regex = new Regex(@"\<\!\[CDATA\[(?<text>[^\]]*)\]\]\>", options);
string         input = @"<![CDATA[<table><tr><td>Approved</td></tr></table>]]>";

// Check for match
bool   isMatch = regex.IsMatch(input);
if( isMatch )
  Match   match = regex.Match(input);
  string   HTMLtext = match.Groups["text"].Value;
end if

The variable "input" is here to use the input pattern you entered.

+8
source

I know this may seem incredibly simple, but have you tried string.Replace ()?

string x = "<![CDATA[<table><tr><td>Approved</td></tr></table>]]>";
string y = x.Replace("<![CDATA[", string.Empty).Replace("]]>", string.Empty);

There are probably more efficient ways to handle this, but maybe you need something easy ...

+4
source

, , , :

/<!\[CDATA\[(.*?)\]\]>/
+2

The regular expression for finding CDATA partitions will be:

(?:<!\[CDATA\[)(.*?)(?:\]\]>)
+1
source
Regex r = new Regex("(?<=<!\[CDATA\[).*?(?=\]\])");
0
source

Why do you want to use Regex for such a simple task? Try the following:

str = str.Trim().Substring(9);
str = str.Substring(0, str.Length-3);
0
source

Source: https://habr.com/ru/post/1707484/


All Articles