如何从字符串中获取这些值?

001*_*001 2 c# asp.net string

webservice返回以下字符串

"ID:xxxx状态:yyyy"

如何在没有"ID:"文本的情况下获取值ID值,如果没有"Status:"文本,则获取"Status"值.

Id值应为xxxx状态值应为yyyy

值长度未知.

Ani*_*Ani 8

一种方法是使用正则表达式.

这样做的好处是"自然地"验证Web服务返回的字符串是否符合您预期的格式,从而可以轻松处理错误的输入.

例如:

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;
Run Code Online (Sandbox Code Playgroud)
^         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
Run Code Online (Sandbox Code Playgroud)

如果你能澄清什么xxxxyyyy可以(字母,数字等),我们可能能够提供更强大的正则表达式.