Reputation: 25
I'm trying to extract a value from a string using regex. The string looks like this:
<faultcode><![CDATA[900015The new password is not long enough. PasswordMinimumLength is 6.]]></faultcode>
I am trying to diplay only the error message to end user.
Upvotes: 0
Views: 423
Reputation: 8232
Updated to correspond with the question edit:
var xml = XElement.Parse(yourString);
var allText = xml.Value;
var stripLeadingNumbers = Regex.Match(xml.Value, @"^\d*(.*)").Groups[1].Value;
Upvotes: 0
Reputation: 141703
First, and foremost, using regex to parse XML / HTML is bad.
Now, by error message I assume you mean the text, not including the numbers. An expression like so would probably do the trick:
\<([^>]+)\><!\[CDATA\[\d*(.*)\]\]>\</\1\>
The error message will be in the second group. This will work with the sample that you have given, but I'd sooner use XDocument
or XmlDocument
to parse it. If you are using C#, there really isn't a good reason to not use either of those classes.
Upvotes: 0
Reputation: 273864
The only sensible thing is to load it into an XElement
(or XDocument, XmlDocument) and extract the Value from the CDATA element.
XElement e = XElement.Parse(xmlSnippet);
string rawMsg = (e.FirstNode as XCData).Value;
string msg = rawMsg.Substring("900015".Length);
Upvotes: 2
Reputation: 663
Since you probably want everything <![CDATA[
and ]]>
this should fit:
<!\[CDATA\[(.+?)\]\]>
Upvotes: 2