c# - 如何从格式化字符串中提取值?

标签 c# parsing input

我得到一个字符串数组,值如下

sNames[0] = "Root | [<root>] | [ID = 1]";
sNames[1] = "Planning | [Root] | [ID = 2]";

我只想从中提取 ID 值 .. 1,2..

现在我这样做:

foreach (var s in sNames)
{
  int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1));
  ...
}

还有其他好的方法吗?

谢谢

最佳答案

您可以使用正则表达式查找 ID(Match() 部分可能不是 100% 正确——留给读者练习)。

var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));

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

相关文章:

python - 在Python中解析用户输入

c# - Entity Framework 更新不更新数据库表

c# - 无法用slowaes(javascript)解密aes密文

c# - 有限制的 ConcurrentDictionary

c# - SOAP 的 WSDL - REST 怎么样?

parsing - Seq.Api.Client.SeqApiException : 400 - The filter expression could not be successfully parsed

c++ - 解析与char c++相关的整数

python - 使用 Python 解析和重新格式化 CSV/文本数据

java - 从 python 脚本执行另一个程序的命令

HTML5 input type=number 和 placeholder 属性