简体   繁体   English

如何从格式化字符串的内部提取值?

[英]How do I extract a value from inside of a formatted string?

I got a string array and values are as follows 我有一个字符串数组,值如下

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

From this I would like to just extract ID value .. 1,2.. 从这里我只想提取ID值.. 1,2 ..

for now am do this as : 现在我这样做是:

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

Is there some other good way to do it ? 还有其他好的方法吗?

Thanks 谢谢

You can use a regex to find the ID (the Match() part may not be 100% correct -- exercise left to the reader). 您可以使用正则表达式查找ID(Match()部分可能不是100%正确-留给读者练习)。

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

You can use regex... 您可以使用正则表达式...

// using System.Text.RegularExpressions
Regex rx = new Regex(@"\[ID\s*=\s*(\d+)\]", RegexOptions.IgnoreCase);
foreach (var s in sNames)
{
  Match m = rx.Match(s);
  if (!m.Success) continue; // Couldn't find ID.
  int id = Convert.ToInt32(m.Groups[1].ToString());
  // ...
}

But now you have two problems . 但是现在你有两个问题 ;-) ;-)

Sounds like a job for regular expressions. 听起来像是正则表达式的工作。 This will match all strings with the pattern of "ID = [some number]" 这将以“ ID = [some number]”的模式匹配所有字符串

using System.Text.RegularExpressions;
...

foreach(string s in sNames) {
  Match m = Regex.Match("ID = ([0-9]+)");
  if(m.Success) {
    int id = Convert.ToInt32(m.Groups[1]);
  }
}

Regular expressions is the "easiest". 正则表达式是“最简单的”。 With the caveat of course that there's a huge learning curve for regex. 需要注意的是,正则表达式的学习曲线很大。

Regex rx = new Regex(@"\[ID\s*=\s*(?<id>\d+)\]");
Match m = rx.Match(str);
string id = m.Groups["id"].Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM