简体   繁体   中英

Regex to parse out html from CDATA with C#

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

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

Thanks!

The expression to handle your example would be

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

Where the group "text" will contain your HTML.

The C# code you need is:

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 "input" variable is in there just to use the sample input you provided

I know this might 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 it might be that you want something that easy...

没有太多细节,但如果没有你没有描述的复杂性,一个非常简单的正则表达式应该匹配它:

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

找到CDATA部分的正则表达式将是:

(?:<!\[CDATA\[)(.*?)(?:\]\]>)

Why do you want to use Regex for such a simple task? Try this one:

str = str.Trim().Substring(9);
str = str.Substring(0, str.Length-3);
Regex r = new Regex("(?<=<!\[CDATA\[).*?(?=\]\])");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM