[英]How do I extract a value from inside of a formatted string?
我有一个字符串数组,值如下
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));
您可以使用正则表达式...
// 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());
// ...
}
但是现在你有两个问题 。 ;-)
听起来像是正则表达式的工作。 这将以“ 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]);
}
}
正则表达式是“最简单的”。 需要注意的是,正则表达式的学习曲线很大。
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.