views:

65

answers:

2

The webservice returns the following string

"ID: xxxx Status: yyyy"

How do I get the value ID value without the "ID :" text, and "Status" value without the "Status: " text.

Id value should be xxxx Status value should be yyyy

the value length is unknown.

+8  A: 

One way would be with a regular expression.

This has the advantage of 'naturally' validating that the string returned by the web-service matches your expected format, allowing you to easily deal with bad input.

For example:

Regex regex = new Regex(@"^ID:\s*(.+)\s*Status:\s*(.+)$");
Match match = regex.Match(input);

// If the input doesn't match the expected format..
if (!match.Success)
    throw new ArgumentException("...");

string id = match.Groups[1].Value; // Group 0 is the whole match
string status = match.Groups[2].Value;

^         Start of string
ID:       Verbatim text
\s*       0 or more whitespaces
(.+)      'ID' group (you can use a named group if you like)
\s*       0 or more whitespaces
Status:   Verbatim text
\s*       0 or more whitespaces
(.+)      'Status' group
$         End of string

If you can clarify what xxxx and yyyy can be (alphabets, numbers, etc.), we might be able to provide a more robust regular expression.

Ani
Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems., just messing with you.
Yuriy Faktorovich
Haha, alright. I've heard that one. In this case, I think its use is justified if only to allow for easy validation.
Ani
Assuming validation is needed, and the performance overhead compared to string parsing isn't a problem. You're also using `\s` which includes more th an just spaces. I'd also name the groups and place the comments straight into the regex.
Yuriy Faktorovich
I like your detailed description of the `RegEx`
Øyvind Bråthen
@Yuriy Faktorovich: Space vs any white-space hasn't been specified, I inferred that from the example. You're right about *possible* issues with using regex in performance-critical situations, but that hasn't been mentioned. As for validation, I would think it's almost certainly necessary when one is parsing data sent over by a web-service.
Ani
@Ani I still can't believe \s includes new lines.
Yuriy Faktorovich
+1 I like the way you explain and breakdown the regex. Really good for a regex noob like myself
Ahmad
+2  A: 

Use something like this:

string s = "ID: xxxx Status: yyyy";
string[] words = s.Split(' ');
string id = s[1];
string status = s[3];

You can cast/convert the value to other data types as may be required.

Kangkan
Not a very robust solution. What if either `ID` or `Status` contains a space?
Øyvind Bråthen
That is right. I assumed them to be a string-without-space or a numeric value.
Kangkan