网络服务返回以下字符串
“ID:xxxx 状态:yyyy”
如何在没有“ID :”文本的情况下获取值 ID 值,以及在没有“Status:”文本的情况下获取“Status”值。
Id 值应该是 xxxx 状态值应该是 yyyy
值长度未知。
最佳答案
一种方法是使用正则表达式。
这具有“自然地”验证网络服务返回的字符串是否符合您预期的格式的优势,让您可以轻松处理错误的输入。
例如:
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
如果您能阐明 xxxx
和 yyyy
可以是什么(字母、数字等),我们也许能够提供更强大的正则表达式。
关于c# - 如何从字符串中获取这些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4057264/