0

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.

9
  • And, what value are you looking for? Commented Dec 14, 2011 at 13:12
  • Which value are you trying to extract? Commented Dec 14, 2011 at 13:12
  • 2
    Is there a chance you're parsing XML yourself instead of using a tool? Commented Dec 14, 2011 at 13:12
  • i need to parse xml myself without using any tool. Commented Dec 14, 2011 at 13:14
  • Is <![CDATA[ always appears in start of your string? and ]]> in end of string? Commented Dec 14, 2011 at 13:15

4 Answers 4

2

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

<!\[CDATA\[(.+?)\]\]>
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

Assuming the &lt; is actually < in the data.
0

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.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.