agnikhil82
agnikhil82

Reputation: 25

extract a value from a string using regex

I'm trying to extract a value from a string using regex. The string looks like this:

<faultcode>&lt;![CDATA[900015The new password is not long enough. PasswordMinimumLength is 6.]]&gt;</faultcode>

I am trying to diplay only the error message to end user.

Upvotes: 0

Views: 423

Answers (4)

Quick Joe Smith
Quick Joe Smith

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

vcsjones
vcsjones

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:

\<([^>]+)\>&lt;!\[CDATA\[\d*(.*)\]\]&gt;\</\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

Henk Holterman
Henk Holterman

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

luastoned
luastoned

Reputation: 663

Since you probably want everything <![CDATA[ and ]]> this should fit:

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

Upvotes: 2

Related Questions