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

标签 c# asp.net string

网络服务返回以下字符串

“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

如果您能阐明 xxxxyyyy 可以是什么(字母、数字等),我们也许能够提供更强大的正则表达式。

关于c# - 如何从字符串中获取这些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4057264/

相关文章:

javascript - 使用 JavaScript 执行带/不带重音字符的文本匹配

c# - 在 C# 的 Unity 注入(inject)容器中调用 RegisterType 的顺序有关系吗?

c# - 为什么 null 合并运算符会破坏我在 c# 中的字符串赋值?

c# - 在 C# 中根据天数获取月数

c# - 在 .net 中使用 OracleCommand 时,机器上是否必须安装 OracleClient,或者 .net 是否涵盖了这一点?

java - 更换琴弦部件

c# - 如何从 PKCS#7 中提取 PKCS#1 签名

c# - OnTriggerEnter 触发太迟

c# - LINQ 和枚举作为 IQueryable

c# - 如何从 XDocument 获取 Xml 作为字符串?